我正在使用此http://www.codeproject.com/Articles/31944/Implementing-a-TextReader-to-extract-various-files,而且它主要是在工作。
我编写了这个测试来检查Filter是否会从字节数组中按预期读取。
private const string ExpectedText = "This is a test!";
[Test]
public void FilterReader_RtfBytes_TextMatch()
{
var bytes = File.ReadAllBytes(@"Test Documents\DocTest.rtf");
var reader = new FilterReader(bytes, ".rtf");
reader.Init();
var actualText = reader.ReadToEnd();
StringAssert.Contains(ExpectedText, actualText);
}
测试失败了ErrorCode : FILTER_E_ACCESS,当我给它文件名时,它工作正常。
new FilterReader(@"Test Documents\DocTest.rtf", ".rtf"); <-- works
我很困惑为什么会这样。我查看了代码,似乎是返回错误的rtf过滤器dll。哪个更令人费解。
它适用于其他文件类型,例如; .doc,.docx,.pdf
答案 0 :(得分:2)
FilterReader(byte[] bytes, string extension)
时,使用IPersistStream从内存加载内容,当FilterReader(string path, string extension)
时 - IPersistFile用于从文件加载
为什么rtf-ifilter在与IPersistStream一起使用时会返回错误我担心因为源代码没有打开而无法知道
在我的情况下,我在下一个方法中封装了构造函数和重构代码中特定的过滤器:
public void Init()
- 方法实现一个自定义构造函数public FilterReader(string fileName, string extension, uint blockSize = 0x2000)
:
#region Contracts
Contract.Requires(!string.IsNullOrEmpty(fileName));
Contract.Requires(!string.IsNullOrEmpty(extension));
Contract.Requires(blockSize > 1);
#endregion
const string rtfExtension = ".rtf";
FileName = fileName;
Extension = extension;
BufferSize = blockSize;
_buffer = new char[ActBufferSize];
// ! Take into account that Rtf-file can be loaded only using IPersistFile.
var doUseIPersistFile = string.Compare(rtfExtension, extension, StringComparison.InvariantCultureIgnoreCase) == 0;
// Initialize _filter instance.
try
{
if (doUseIPersistFile)
{
// Load content using IPersistFile.
_filter = FilterLoader.LoadIFilterFromIPersistFile(FileName, Extension);
}
else
{
// Load content using IPersistStream.
using (var stream = new FileStream(path: fileName, mode: FileMode.Open, access: FileAccess.Read, share: FileShare.Read))
{
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
_filter = FilterLoader.LoadIFilterFromStream(buffer, Extension);
}
}
}
catch (FileNotFoundException)
{
throw;
}
catch (Exception e)
{
throw new AggregateException(message: string.Format("Filter Not Found or Loaded for extension '{0}'.", Extension), innerException: e);
}