Determine the file type

A file type is a standard way that information is encoded for storage in a computer file. For example, Microsoft Word (.docx) and Adobe PDF (.pdf) are two different file types.

Using GroupDocs.Viewer, you can determine the file type in one of the following ways:

Determine the file type by the file extension

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

The following code snippet shows how to determine a file type using the file extension:

// Specify a file extension.
string extension = ".docx";
// Set a file type using the extension.
FileType fileType = FileType.FromExtension(extension);
// Display the extension and the file type.
Console.WriteLine($"Extension {extension}; File type: {fileType}.");

The following image shows a sample console output:

Determine file type by media type

If you receive a file via the Internet, you can check its media type header using the FromMediaType() method of the FileType class.

The following code snippet shows how to determine a file type using the media header:

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

The following image shows a sample console output:

Determine file type by the stream

When you do not know a file extension or media type header, you can try determining file type by using the FromStream() method of the FileType class. GroupDocs.Viewer will try reading the signature and mapping it to the file type.

The following code snippet shows how to determine a file type using the file signature:

using (Stream stream = File.OpenRead("sample.docx"))
{
    FileType fileType = FileType.FromStream(stream);
    Console.WriteLine($"File type: {fileType}.");
}

The following image shows a sample console output: