Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace JasonStorey
- {
- public static class Files
- {
- public static async Task<T> ReadJsonAsync<T>(string path) =>
- JsonConvert.DeserializeObject<T>(await ReadAllTextAsync(path));
- public static Task WriteJsonAsync<T>(T item, string path) =>
- WriteAllTextAsync(path, JsonConvert.SerializeObject(item));
- public static async Task ReadCsvAsync(string filePath, Action<string[]> processRowAction)
- {
- using var reader = new StreamReader(filePath);
- while (!reader.EndOfStream)
- {
- var line = await reader.ReadLineAsync();
- var values = line.Split(',');
- processRowAction(values);
- }
- }
- public static async ValueTask WriteCsvAsync(string filePath, string[][] data)
- {
- if (filePath is null)
- throw new ArgumentNullException(nameof(filePath));
- if (data is null)
- throw new ArgumentNullException(nameof(data));
- const int initialCapacity = 1024;
- await using var fileStream = new FileStream(
- filePath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true);
- await using var textWriter = new StreamWriter(fileStream, new UTF8Encoding(false), initialCapacity, true);
- var stringBuilder = new StringBuilder(initialCapacity);
- foreach (var row in data)
- {
- var firstValue = true;
- foreach (var value in row)
- {
- if (!firstValue) stringBuilder.Append(',');
- stringBuilder.Append(value);
- firstValue = false;
- }
- stringBuilder.AppendLine();
- }
- await textWriter.WriteAsync(stringBuilder.ToString());
- }
- public static async Task PerformTaskOnFileAsync(string filePath, Func<string, CancellationToken, Task> task, CancellationToken cancellationToken = default)
- {
- if (!Exists(filePath))
- throw new ArgumentException("File does not exist", nameof(filePath));
- string backupFilePath = filePath + ".bak";
- try
- {
- Copy(filePath, backupFilePath);
- SetAttributes(backupFilePath, FileAttributes.Hidden);
- await task(filePath, cancellationToken);
- Delete(backupFilePath);
- }
- catch (OperationCanceledException)
- {
- Delete(filePath);
- Move(backupFilePath, filePath);
- throw;
- }
- catch (Exception)
- {
- Delete(filePath);
- Move(backupFilePath, filePath);
- throw;
- }
- }
- public static async Task WriteXmlAsync<T>(string filePath, T data) where T : class
- {
- var serializer = new XmlSerializer(typeof(T));
- using (var streamWriter = new StreamWriter(filePath))
- {
- await Task.Run(() => serializer.Serialize(streamWriter, data));
- }
- }
- public static async Task<T> ReadXmlAsync<T>(string filePath) where T : class
- {
- var serializer = new XmlSerializer(typeof(T));
- using var streamReader = new StreamReader(filePath);
- return await Task.Run(() => serializer.Deserialize(streamReader) as T);
- }
- public static async Task<string> ReadXmlAsJsonAsync(string filePath)
- {
- var xmlDoc = new XmlDocument();
- await Task.Run(() => xmlDoc.Load(filePath));
- return JsonConvert.SerializeXmlNode(xmlDoc);
- }
- public static async Task<List<IniSection>> ReadIniAsync(string filePath)
- {
- if (!Exists(filePath))
- throw new FileNotFoundException("The specified file does not exist.");
- var lines = await ReadAllLinesAsync(filePath);
- return lines
- .Where(line => !string.IsNullOrWhiteSpace(line) && !line.StartsWith(";"))
- .Aggregate(new List<IniSection>(), (sections, line) =>
- {
- if (line.StartsWith("[") && line.EndsWith("]"))
- {
- var sectionName = line.Substring(1, line.Length - 2);
- sections.Add(new IniSection { Name = sectionName, KeyValues = new Dictionary<string, string>() });
- }
- else if (sections.Any())
- {
- var keyValue = line.Split('=');
- if (keyValue.Length != 2) return sections;
- var key = keyValue[0].Trim();
- var value = keyValue[1].Trim();
- sections.Last().KeyValues[key] = value;
- }
- return sections;
- });
- }
- public static async Task WriteIniAsync(string filePath, List<IniSection> sections)
- {
- await using var writer = new StreamWriter(filePath);
- foreach (var section in sections)
- {
- await writer.WriteLineAsync("[" + section.Name + "]");
- foreach (var keyValuePair in section.KeyValues)
- await writer.WriteLineAsync(keyValuePair.Key + "=" + keyValuePair.Value);
- await writer.WriteLineAsync();
- }
- }
- public static void OpenDirectory(string path)
- {
- if (Exists(path)) path = Path.GetDirectoryName(path);
- if (Directory.Exists(path)) Start(path);
- }
- }
- [Serializable]
- public class IniSection
- {
- public string Name { get; set; }
- public Dictionary<string, string> KeyValues { get; set; }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement