Back to Devexpress

IDocumentFormatDetector.Detect(Stream) Method

blazor-devexpress-dot-blazor-dot-richedit-dot-idocumentformatdetector-dot-detect-x28-system-dot-io-dot-stream-x29.md

latest2.9 KB
Original Source

IDocumentFormatDetector.Detect(Stream) Method

Returns the format of a file contained in the stream.

Namespace : DevExpress.Blazor.RichEdit

Assembly : DevExpress.Blazor.v25.2.dll

NuGet Package : DevExpress.Blazor

Declaration

csharp
DocumentFormat Detect(
    Stream stream
)

Parameters

NameTypeDescription
streamStream

The stream that contains the document.

|

Returns

TypeDescription
DocumentFormat

The format of the document.

|

Remarks

The Rich Text Editor automatically detects the document’s format when you call the LoadDocumentAsync(Stream, CancellationToken) method to load a document from a specified stream. Override the Detect method to implement your own file format detection logic.

The following code snippet implements the IDocumentFormatDetector interface and its Detect methods.

csharp
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;
  }
}
csharp
// Registers the MyDocumentFormatDetector in the application's services
public void ConfigureServices(IServiceCollection services) {
  // ...
  services.AddSingleton<IDocumentFormatDetector>(new MyDocumentFormatDetector());
}

See Also

Document Management in Blazor Rich Text Editor

IDocumentFormatDetector Interface

IDocumentFormatDetector Members

DevExpress.Blazor.RichEdit Namespace