Skip to main content

IDocumentFormatDetector Interface

Declares methods that detect the format of document files.

Namespace: DevExpress.Blazor.RichEdit

Assembly: DevExpress.Blazor.v24.1.dll

NuGet Package: DevExpress.Blazor

Declaration

public interface IDocumentFormatDetector

Remarks

Implement the IDocumentFormatDetector interface to provide 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