FileFormatUtilDetectFileFormat Method (Stream)

Detects and returns the information about a format of a document stored in a stream.

Namespace:  Aspose.Words
Assembly:  Aspose.Words (in Aspose.Words.dll) Version: 20.3
Syntax
public static FileFormatInfo DetectFileFormat(
	Stream stream
)

Parameters

stream
Type: System.IOStream
The stream.

Return Value

Type: FileFormatInfo
A FileFormatInfo object that contains the detected information.
Remarks

The stream must be positioned at the beginning of the document.

When this method returns, the position in the stream is restored to the original position.

Even if this method detects the document format, it does not guarantee that the specified document is valid. This method only detects the document format by reading data that is sufficient for detection. To fully verify that a document is valid you need to load the document into a Document object.

This method throws FileCorruptedException when the format is recognized, but the detection cannot complete because of corruption.

Examples
Shows how to use the FileFormatUtil methods to detect the format of a document without any extension and save it with the correct file extension.
// Load the document without a file extension into a stream and use the DetectFileFormat method to detect it's format
// These are both times where you might need extract the file format as it's not visible
// The file format of this document is actually ".doc"
FileStream docStream = File.OpenRead(MyDir + "Word document with missing file extension");
FileFormatInfo info = FileFormatUtil.DetectFileFormat(docStream);

// Retrieve the LoadFormat of the document
LoadFormat loadFormat = info.LoadFormat;

// Let's show the different methods of converting LoadFormat enumerations to SaveFormat enumerations
// 
// Method #1
// Convert the LoadFormat to a String first for working with. The String will include the leading dot in front of the extension
string fileExtension = FileFormatUtil.LoadFormatToExtension(loadFormat);
// Now convert this extension into the corresponding SaveFormat enumeration
SaveFormat saveFormat = FileFormatUtil.ExtensionToSaveFormat(fileExtension);

// Method #2
// Convert the LoadFormat enumeration directly to the SaveFormat enumeration
saveFormat = FileFormatUtil.LoadFormatToSaveFormat(loadFormat);

// Load a document from the stream.
Document doc = new Document(docStream);

// Save the document with the original file name, " Out" and the document's file extension
doc.Save(
    ArtifactsDir + "File.SaveToDetectedFileFormat" + FileFormatUtil.SaveFormatToExtension(saveFormat));
See Also