You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

FileManager.cs 2.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using Splat;
  2. using System;
  3. using System.IO;
  4. using System.IO.Compression;
  5. using System.Text;
  6. namespace Shadowsocks.WPF.Utils
  7. {
  8. public static class FileManager
  9. {
  10. public static bool ByteArrayToFile(string fileName, byte[] content)
  11. {
  12. try
  13. {
  14. using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
  15. fs.Write(content, 0, content.Length);
  16. return true;
  17. }
  18. catch (Exception ex)
  19. {
  20. LogHost.Default.Error(ex, "");
  21. }
  22. return false;
  23. }
  24. public static void UncompressFile(string fileName, byte[] content)
  25. {
  26. // Because the uncompressed size of the file is unknown,
  27. // we are using an arbitrary buffer size.
  28. byte[] buffer = new byte[4096];
  29. int n;
  30. using(var fs = File.Create(fileName))
  31. using (var input = new GZipStream(new MemoryStream(content),
  32. CompressionMode.Decompress, false))
  33. {
  34. while ((n = input.Read(buffer, 0, buffer.Length)) > 0)
  35. {
  36. fs.Write(buffer, 0, n);
  37. }
  38. }
  39. }
  40. public static string NonExclusiveReadAllText(string path)
  41. {
  42. return NonExclusiveReadAllText(path, Encoding.Default);
  43. }
  44. public static string NonExclusiveReadAllText(string path, Encoding encoding)
  45. {
  46. try
  47. {
  48. using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  49. using (var sr = new StreamReader(fs, encoding))
  50. {
  51. return sr.ReadToEnd();
  52. }
  53. }
  54. catch (Exception ex)
  55. {
  56. LogHost.Default.Error(ex, "");
  57. throw;
  58. }
  59. }
  60. }
  61. }