IDocumentFormatDetector.Detect(String) Method
Returns the format of a file with the specified path.
Namespace: DevExpress.Blazor.RichEdit
Assembly: DevExpress.Blazor.v24.1.dll
NuGet Package: DevExpress.Blazor
Declaration
DocumentFormat Detect(
string filePath
)
Parameters
Name | Type | Description |
---|---|---|
filePath | String | The path to the document. |
Returns
Type | Description |
---|---|
DocumentFormat | The format of the document. |
Remarks
The Rich Text Editor automatically detects the document’s format when you call the LoadDocumentAsync(String, CancellationToken) method to load a document from a specified file path. Override the Detect
method to implement your own file format detection logic.
The following code snippet implements the IDocumentFormatDetector interface and its Detect
methods.
public class MyDocumentFormatDetector : IDocumentFormatDetector {
public DocumentFormat Detect(string filePath) {
if(!File.Exists(filePath)) {
switch(Path.GetExtension(filePath)) {
case ".rtf":
return DocumentFormat.Rtf;
case ".docx":
return DocumentFormat.OpenXml;
default:
return DocumentFormat.PlainText;
}
} else {
using(var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) {
return Detect(stream);
}
}
}
public DocumentFormat Detect(Stream stream) {
if(!stream.CanSeek)
return DocumentFormat.PlainText;
stream.Seek(0, SeekOrigin.Begin);
var head = new byte[5];
stream.Read(head, 0, head.Length);
stream.Seek(0, SeekOrigin.Begin);
if(Encoding.ASCII.GetString(head, 0, 2) == "PK")
return DocumentFormat.OpenXml;
else if(Encoding.ASCII.GetString(head) == "{\\rtf")
return DocumentFormat.Rtf;
return DocumentFormat.PlainText;
}
}
// Registers the MyDocumentFormatDetector in the application's services
public void ConfigureServices(IServiceCollection services) {
// ...
services.AddSingleton<IDocumentFormatDetector>(new MyDocumentFormatDetector());
}
See Also