-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCSVWriter.cs
More file actions
72 lines (69 loc) · 2.34 KB
/
CSVWriter.cs
File metadata and controls
72 lines (69 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
namespace CSVLibrary
{
public class CSVWriter<T>where T : class, new()
{
string _Path = "";
/// <summary>
///
/// </summary>
/// <param name="path">Path were the File should be saved to INCLUDING .csv</param>
public CSVWriter(string path)
{
_Path = path;
}
/// <summary>
/// Writes all Properties of t to a csv file
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="toWrite">needs to have an empty constructor</param>
/// <param name="seperator">Standard to ';' for csv files</param>
public void Write(T toWrite, bool append = false, char seperator = ';')
{
using (StreamWriter sw = new StreamWriter(_Path, append))
{
StringBuilder writeThis = new StringBuilder();
var type = toWrite.GetType();
try
{
foreach (var property in type.GetProperties().Where(p => p.CanWrite))
{
writeThis.Append($"{property.Name}={property.PropertyType.FullName}={property.GetValue(toWrite)};");
}
}
catch (Exception e)
{
throw e;
}
sw.Write(writeThis);
}
}
public void Write(List<T> toWrite, char seperator = ';')
{
using (StreamWriter sw = new StreamWriter(_Path, false))
{
StringBuilder writeThis = new StringBuilder();
try
{
foreach (var itemToWrite in toWrite)
{
foreach (var property in itemToWrite.GetType().GetProperties().Where(p => p.CanWrite))
{
writeThis.Append($"{property.Name}={property.PropertyType}={property.GetValue(itemToWrite)};");
}
writeThis.AppendLine();
}
sw.Write(writeThis);
}
catch (Exception e)
{
throw e;
}
}
}
}
}