Advertisement
apieceoffruit

Files

Mar 13th, 2023
1,521
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.93 KB | None | 0 0
  1. namespace JasonStorey
  2. {
  3.     public static class Files
  4.     {
  5.         public static async Task<T> ReadJsonAsync<T>(string path) =>
  6.             JsonConvert.DeserializeObject<T>(await ReadAllTextAsync(path));
  7.  
  8.         public static Task WriteJsonAsync<T>(T item, string path) =>
  9.             WriteAllTextAsync(path, JsonConvert.SerializeObject(item));
  10.  
  11.         public static async Task ReadCsvAsync(string filePath, Action<string[]> processRowAction)
  12.         {
  13.             using var reader = new StreamReader(filePath);
  14.             while (!reader.EndOfStream)
  15.             {
  16.                 var line = await reader.ReadLineAsync();
  17.                 var values = line.Split(',');
  18.                 processRowAction(values);
  19.             }
  20.         }
  21.  
  22.         public static async ValueTask WriteCsvAsync(string filePath, string[][] data)
  23.         {
  24.             if (filePath is null)
  25.                 throw new ArgumentNullException(nameof(filePath));
  26.  
  27.             if (data is null)
  28.                 throw new ArgumentNullException(nameof(data));
  29.  
  30.             const int initialCapacity = 1024;
  31.  
  32.             await using var fileStream = new FileStream(
  33.                 filePath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true);
  34.  
  35.             await using var textWriter = new StreamWriter(fileStream, new UTF8Encoding(false), initialCapacity, true);
  36.  
  37.             var stringBuilder = new StringBuilder(initialCapacity);
  38.  
  39.             foreach (var row in data)
  40.             {
  41.                 var firstValue = true;
  42.  
  43.                 foreach (var value in row)
  44.                 {
  45.                     if (!firstValue) stringBuilder.Append(',');
  46.                     stringBuilder.Append(value);
  47.                     firstValue = false;
  48.                 }
  49.  
  50.                 stringBuilder.AppendLine();
  51.             }
  52.  
  53.             await textWriter.WriteAsync(stringBuilder.ToString());
  54.         }
  55.  
  56.         public static async Task PerformTaskOnFileAsync(string filePath, Func<string, CancellationToken, Task> task, CancellationToken cancellationToken = default)
  57.         {
  58.             if (!Exists(filePath))
  59.                 throw new ArgumentException("File does not exist", nameof(filePath));
  60.             string backupFilePath = filePath + ".bak";
  61.             try
  62.             {
  63.                 Copy(filePath, backupFilePath);
  64.                 SetAttributes(backupFilePath, FileAttributes.Hidden);
  65.                 await task(filePath, cancellationToken);
  66.                 Delete(backupFilePath);
  67.             }
  68.             catch (OperationCanceledException)
  69.             {
  70.                 Delete(filePath);
  71.                 Move(backupFilePath, filePath);
  72.                 throw;
  73.             }
  74.             catch (Exception)
  75.             {
  76.                 Delete(filePath);
  77.                 Move(backupFilePath, filePath);
  78.                 throw;
  79.             }
  80.         }
  81.        
  82.         public static async Task WriteXmlAsync<T>(string filePath, T data) where T : class
  83.         {
  84.             var serializer = new XmlSerializer(typeof(T));
  85.             using (var streamWriter = new StreamWriter(filePath))
  86.             {
  87.                 await Task.Run(() => serializer.Serialize(streamWriter, data));
  88.             }
  89.         }
  90.  
  91.         public static async Task<T> ReadXmlAsync<T>(string filePath) where T : class
  92.         {
  93.             var serializer = new XmlSerializer(typeof(T));
  94.             using var streamReader = new StreamReader(filePath);
  95.             return await Task.Run(() => serializer.Deserialize(streamReader) as T);
  96.         }
  97.  
  98.         public static async Task<string> ReadXmlAsJsonAsync(string filePath)
  99.         {
  100.             var xmlDoc = new XmlDocument();
  101.             await Task.Run(() => xmlDoc.Load(filePath));
  102.             return JsonConvert.SerializeXmlNode(xmlDoc);
  103.         }
  104.        
  105.         public static async Task<List<IniSection>> ReadIniAsync(string filePath)
  106.         {
  107.             if (!Exists(filePath))
  108.                 throw new FileNotFoundException("The specified file does not exist.");
  109.  
  110.             var lines = await ReadAllLinesAsync(filePath);
  111.  
  112.             return lines
  113.                 .Where(line => !string.IsNullOrWhiteSpace(line) && !line.StartsWith(";"))
  114.                 .Aggregate(new List<IniSection>(), (sections, line) =>
  115.                 {
  116.                     if (line.StartsWith("[") && line.EndsWith("]"))
  117.                     {
  118.                         var sectionName = line.Substring(1, line.Length - 2);
  119.                         sections.Add(new IniSection { Name = sectionName, KeyValues = new Dictionary<string, string>() });
  120.                     }
  121.                     else if (sections.Any())
  122.                     {
  123.                         var keyValue = line.Split('=');
  124.                         if (keyValue.Length != 2) return sections;
  125.                         var key = keyValue[0].Trim();
  126.                         var value = keyValue[1].Trim();
  127.                         sections.Last().KeyValues[key] = value;
  128.                     }
  129.                     return sections;
  130.                 });
  131.         }
  132.  
  133.         public static async Task WriteIniAsync(string filePath, List<IniSection> sections)
  134.         {
  135.             await using var writer = new StreamWriter(filePath);
  136.             foreach (var section in sections)
  137.             {
  138.                 await writer.WriteLineAsync("[" + section.Name + "]");
  139.                 foreach (var keyValuePair in section.KeyValues)
  140.                     await writer.WriteLineAsync(keyValuePair.Key + "=" + keyValuePair.Value);
  141.                 await writer.WriteLineAsync();
  142.             }
  143.         }
  144.  
  145.         public static void OpenDirectory(string path)
  146.         {
  147.             if (Exists(path)) path = Path.GetDirectoryName(path);
  148.             if (Directory.Exists(path)) Start(path);
  149.         }
  150.     }
  151.  
  152.     [Serializable]
  153.     public class IniSection
  154.     {
  155.         public string Name { get; set; }
  156.         public Dictionary<string, string> KeyValues { get; set; }
  157.     }
  158. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement