FileParserInfo.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.IO;
  3. using System.Reflection;
  4. namespace PixiEditor.SDK.FileParsers
  5. {
  6. internal abstract class FileParserInfo<TParser, T>
  7. where TParser : FileParser<T>
  8. {
  9. public Type ParserType { get; }
  10. public bool Enabled { get; set; } = true;
  11. public string[] SupportedFileExtensions { get; set; }
  12. private ConstructorInfo Constructor { get; }
  13. public TParser Create(Stream stream)
  14. {
  15. TParser parser = (TParser)Constructor.Invoke(null);
  16. parser.Stream = stream;
  17. return parser;
  18. }
  19. public TParser Create(Stream stream, string path)
  20. {
  21. TParser parser = Create(stream);
  22. parser.FileInfo = new FileInfo(path);
  23. return parser;
  24. }
  25. public FileParserInfo(Type parserType)
  26. {
  27. FileParserAttribute fileParserAttribute;
  28. if ((fileParserAttribute = parserType.GetCustomAttribute<FileParserAttribute>()) is null)
  29. {
  30. throw new ParserException(parserType, $"'{parserType}' needs an {nameof(FileParserAttribute)}");
  31. }
  32. SupportedFileExtensions = fileParserAttribute.FileExtensions;
  33. Constructor = parserType.GetConstructor(Type.EmptyTypes);
  34. if (Constructor is null)
  35. {
  36. throw new ParserException(parserType, $"'{parserType}' needs an constructor that no parameters");
  37. }
  38. ParserType = parserType;
  39. }
  40. }
  41. }