ArchiveEncoding.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Text;
  3. namespace SharpCompress.Common
  4. {
  5. public class ArchiveEncoding
  6. {
  7. /// <summary>
  8. /// Default encoding to use when archive format doesn't specify one.
  9. /// </summary>
  10. public Encoding Default { get; set; }
  11. /// <summary>
  12. /// ArchiveEncoding used by encryption schemes which don't comply with RFC 2898.
  13. /// </summary>
  14. public Encoding Password { get; set; }
  15. /// <summary>
  16. /// Set this encoding when you want to force it for all encoding operations.
  17. /// </summary>
  18. public Encoding Forced { get; set; }
  19. /// <summary>
  20. /// Set this when you want to use a custom method for all decoding operations.
  21. /// </summary>
  22. /// <returns>string Func(bytes, index, length)</returns>
  23. public Func<byte[], int, int, string> CustomDecoder { get; set; }
  24. public ArchiveEncoding()
  25. {
  26. #if NETSTANDARD1_0
  27. Default = Encoding.GetEncoding("cp437");
  28. Password = Encoding.GetEncoding("cp437");
  29. #else
  30. Default = Encoding.GetEncoding(437);
  31. Password = Encoding.GetEncoding(437);
  32. #endif
  33. }
  34. #if NETSTANDARD1_3 || NETSTANDARD2_0
  35. static ArchiveEncoding()
  36. {
  37. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  38. }
  39. #endif
  40. public string Decode(byte[] bytes)
  41. {
  42. return Decode(bytes, 0, bytes.Length);
  43. }
  44. public string Decode(byte[] bytes, int start, int length)
  45. {
  46. return GetDecoder().Invoke(bytes, start, length);
  47. }
  48. public string DecodeUTF8(byte[] bytes)
  49. {
  50. return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
  51. }
  52. public byte[] Encode(string str)
  53. {
  54. return GetEncoding().GetBytes(str);
  55. }
  56. public Encoding GetEncoding()
  57. {
  58. return Forced ?? Default ?? Encoding.UTF8;
  59. }
  60. public Func<byte[], int, int, string> GetDecoder()
  61. {
  62. return CustomDecoder ?? ((bytes, index, count) => GetEncoding().GetString(bytes, index, count));
  63. }
  64. }
  65. }