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

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