TextEncoding.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System.Text;
  2. using MediaBrowser.Model.IO;
  3. using MediaBrowser.Model.TextEncoding;
  4. namespace MediaBrowser.Server.Implementations.TextEncoding
  5. {
  6. public class TextEncoding : IEncoding
  7. {
  8. private readonly IFileSystem _fileSystem;
  9. public TextEncoding(IFileSystem fileSystem)
  10. {
  11. _fileSystem = fileSystem;
  12. }
  13. public byte[] GetASCIIBytes(string text)
  14. {
  15. return Encoding.ASCII.GetBytes(text);
  16. }
  17. public string GetASCIIString(byte[] bytes, int startIndex, int length)
  18. {
  19. return Encoding.ASCII.GetString(bytes, 0, bytes.Length);
  20. }
  21. public Encoding GetFileEncoding(string srcFile)
  22. {
  23. // *** Detect byte order mark if any - otherwise assume default
  24. var buffer = new byte[5];
  25. using (var file = _fileSystem.OpenRead(srcFile))
  26. {
  27. file.Read(buffer, 0, 5);
  28. }
  29. if (buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf)
  30. return Encoding.UTF8;
  31. if (buffer[0] == 0xfe && buffer[1] == 0xff)
  32. return Encoding.Unicode;
  33. if (buffer[0] == 0 && buffer[1] == 0 && buffer[2] == 0xfe && buffer[3] == 0xff)
  34. return Encoding.UTF32;
  35. if (buffer[0] == 0x2b && buffer[1] == 0x2f && buffer[2] == 0x76)
  36. return Encoding.UTF7;
  37. // It's ok - anything aside from utf is ok since that's what we're looking for
  38. return Encoding.Default;
  39. }
  40. }
  41. }