How to determine file type


File type or file format is the way to classify and differentiate one kind of file from another. For example, Microsoft Excel and Adobe PDF are two different file types. The common way to determine the file type is by its extension, so when you have a file e.g. sample.docx you expect that this file will be opened by some text processing application like Microsoft Word. But there are the cases when you don’t know the file type e.g. when the file came from the Internet but you don’t know its name or filename doesn’t have an extension.

Determining file type

GroupDocs.Viewer enables you to determine the file type by file extension, media-type, or raw bytes. The code snippets provided in this article can also be found in our public examples at GitHub.

Determining file-type from the file extension

To determine file type from the file extension use FromExtension() method of FileType class.

string extension = ".docx";
FileType fileType = FileType.FromExtension(extension);
Console.WriteLine($"\nExtension {extension}; File type: {fileType}.");

As you can see from the screenshot below the file type detected correctly.

Determining file-type from the media-type

In case you receive a file from the Internet and you have only its media-type use FromMediaType() method of FileType class.

string mediaType = "application/pdf";
FileType fileType = FileType.FromMediaType(mediaType);
Console.WriteLine($"\nMedia-type {mediaType}; File type: {fileType}.");

The media-type will be mapped to the file type as shown on the screenshot below.

Determining file type form stream or bytes

When you don’t know the name of a file or media-type you can try determining file type by passing stream to FromStream() method of FileType. GroupDocs.Viewer will try reading the file signature and map it to the file type.

using (Stream stream = File.OpenRead("sample.docx"))
    FileType fileType = FileType.FromStream(stream);

    Console.WriteLine($"\nFile path {TestFiles.SAMPLE_DOCX}; File type: {fileType}.");

A similar output would be printed in case of GroupDocs.Viewer detected the file type successfully.

More resources

GitHub Examples

You may easily run the code above and see the feature in action in our GitHub examples:

Free Online App

Along with full-featured .NET library we provide simple but powerful free Apps. You are welcome to view your documents with free to use online GroupDocs Viewer App.