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.1 kB

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