-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoutputter.cs
More file actions
81 lines (72 loc) · 2.46 KB
/
outputter.cs
File metadata and controls
81 lines (72 loc) · 2.46 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
73
74
75
76
77
78
79
80
81
using CsvHelper;
using CsvHelper.Configuration;
using HackBrowserData.BrowsingData;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text.Json;
using JsonSerializer = System.Text.Json.JsonSerializer;
namespace YourNamespace
{
public class OutPutter
{
private readonly bool _json;
private readonly bool _csv;
public OutPutter(string flag)
{
if (flag == "json")
{
_json = true;
}
else
{
_csv = true;
}
}
public void Write(Source data, Stream writer)
{// Assuming your Source objects can be converted to a collection (e.g., a list)
IEnumerable<Source> sourceCollection = new List<Source> { data }; // Create a collection containing your data
if (_json)
{
// JSON serialization code remains the same
using Utf8JsonWriter writerUtf8 = new(writer);
JsonSerializerOptions options = new()
{
WriteIndented = true,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
JsonSerializer.Serialize(writerUtf8, sourceCollection, options);
}
else if (_csv)
{
CsvConfiguration config = new(CultureInfo.CurrentCulture)
{
ShouldQuote = field => true,
};
using CsvWriter csvWriter = new(new StreamWriter(writer), config);
csvWriter.WriteRecords(sourceCollection); // Pass the collection here
}
}
public FileStream CreateFile(string dir, string filename)
{
if (string.IsNullOrEmpty(filename))
{
throw new ArgumentException("Empty filename");
}
if (!string.IsNullOrEmpty(dir))
{
if (!Directory.Exists(dir))
{
_ = Directory.CreateDirectory(dir);
}
}
string filePath = Path.Combine(dir, filename);
return new FileStream(filePath, FileMode.Create, FileAccess.Write);
}
public string Ext()
{
return _json ? "json" : "csv";
}
}
}