Skip to content

Create custom type

Aleksandar J. Mitev edited this page Oct 24, 2022 · 7 revisions

In order to create new identifiable type you should do two important things. The first one is to inherit FileType class. The second one is to have parameterless constructor.

Few moments after you inherit the base class you will notice that he has two constructors with different signatures. All of them accepts name and extension but the difference is in magicBytes that can be used. You should implement only one of them. The reason of this two constructors is because you can face two different scenarios - you will have one array of bytes that can identify your type or you will have two or more arrays that can identify the type and we want to cover both cases.

public FileType(string name, string extension, byte[] magicBytes){}       
public FileType(string name, string extension, byte[][] magicBytesJaggedArray){}       

The first you should use if your custom type has one variation of bytes that identifies it. The second constructor will be helpful in situation where you group some types into one custom type or the type has multiple versions and they are represented by different bytes.

Final result

The description above sounds reasonable, right? Because of that reason your final implementation should be looking like that.

using FileTypeChecker.Abstracts;

public class MyCustomFileType : FileType
{
    private static readonly string name = "My Super Cool Custom Type 1.0";
    private static readonly string extension = "ext";
    private static readonly byte[] magicBytes = new byte[] { 0xAF };

    public MyCustomFileType() : base(name, extension, magicBytes){}
}
using FileTypeChecker.Abstracts;

 public class MyCustomFileTypeWithManyVersions : FileType
 {
     private static readonly string name = "My Super Cool Custom Type 1.0";
     private static readonly string extension = "ext2";
     private static readonly byte[][] magicBytes = { new byte[] { 0xAF }, new byte[] { 0xEF } };

      
    public MyCustomFileTypeWithManyVersions() : base(name, extension, magicBytes ){}
}

Register custom types

Once you are finished with the implementation now it is time to register your own custom type. All types and validation functionalities are initialized once the app is started via reflection. In order your type to be recognized point the assembly where it is located by putting this code in your app configuration method.

FileTypeValidator.RegisterCustomTypes(typeof(MyCustomFileType).Assembly);
Clone this wiki locally