我想从字节数组创建一个新的System.Windows.Xps.Packaging.XpsDocument对象,因为我不想立即将它存储在本地计算机上。
通过使用临时文件,它可以正常工作:
public static XpsDocument OpenXpsDocument(string url)
{
WebClient webClient = new System.Net.WebClient();
byte[] data = webClient.DownloadData(url);
using (BinaryWriter writer = new System.IO.BinaryWriter(File.OpenWrite(xpsTempFilePath)))
{
writer.Write(data);
writer.Flush();
}
XpsDocument xpsDocument = new System.Windows.Xps.Packaging.XpsDocument(xpsTempFilePath, FileAccess.Read);
return xpsDocument;
}
但是,我想要完成的更像是:
public static XpsDocument OpenXpsDocument(string url)
{
WebClient webClient = new WebClient();
byte[] data = webClient.DownloadData(url);
Package package;
using (Stream stream = new MemoryStream(data))
{
package = System.IO.Packaging.Package.Open(stream);
}
XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.SuperFast, url);
return xpsDocument;
}
上述方法的用法如下:
XpsDocument xps = TaxReturnCreator.OpenXpsDocument(tempFileUrl);
documentViewer1.Document = xps.GetFixedDocumentSequence();
并且,使用最后描述的尝试在WPF窗口中显示XPS内容的方法(不保存)使用System.ObjectDisposedException(“无法访问已关闭的流”)崩溃(第一种方法正常工作)。
我是否应该在创建XpsDocument后仍保持Stream打开,或者我错过了其他内容? 也许有人知道一种完全不同/更好的方法,可以将XPS数据作为网络上的字节检索并从数据中创建XpsDocument对象?
答案 0 :(得分:7)
您无法关闭支持XpsDocument的流。您必须允许Package管理后备MemoryStream,这将在收集此Package后收集。执行以下操作可能看起来有些异端:
public static XpsDocument OpenXpsDocument(string url)
{
var webClient = new WebClient();
var data = webClient.DownloadData(url);
var package = System.IO.Packaging.Package.Open(new MemoryStream(data));
var xpsDocument = new XpsDocument(package,
CompressionOption.SuperFast,
url);
return xpsDocument;
}
但这是必须如何做的。
答案 1 :(得分:0)
你应该尝试包括
XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.SuperFast, url);
进入using
区块,即
Package package;
using (Stream stream = new MemoryStream(data))
{
package = System.IO.Packaging.Package.Open(stream);
XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.SuperFast, url);
}
return xpsDocument;