c# - 生成的文件仍然被锁定
问题描述
我正在使用 OpenXML SDK 生成并保存一个 word 文档。
我正在使用“使用”块来创建和处理内存流,以及完成后的 word 文档对象。但是,当尝试打开文件时,我收到该文件仍在被另一个进程使用的错误。查看资源监视器,我发现它是我的 c# 应用程序仍然保持打开状态。当我关闭我的应用程序时,我可以使用该文件
我有以下代码。
private void button2_Click(object sender, EventArgs e)
{
// Create Stream
using (MemoryStream mem = new MemoryStream())
{
// Create Document
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create the document structure and add some text.
mainPart.Document = new Document();
Body docBody = new Body();
mainPart.Document.Append(docBody);
wordDocument.SaveAs(@"E:\Report\word.docx");
// Add your docx content here
wordDocument.Close();
}
}
}
我的理解是否正确
using (MemoryStream mem = new MemoryStream())
应该在块完成时处理 MemoryStream,从而允许另一个进程使用该文件?
谢谢
解决方案
SaveAs
返回一个新的包对象,它表示存储在该文件中的包。你也需要Close
那个包。
wordDocument.SaveAs(@"E:\Report\word.docx").Close();
推荐阅读
- php - 通过 AJAX 成功回显数据对象中返回的单个变量
- html - 导航项目不显示
- vim - 在 Vim 中,如何复制文件中的内容并在命令中使用?
- c - 将两个大数相乘会得出错误的结果
- centos7 - 当我要在节点中开始 slurm 时出错
- apache-httpclient-4.x - Apache HttpClient 4.5:为什么第二个包等待第一个包的ack?
- ruby-on-rails - 弹性豆茎中的克隆环境
- azure-cognitive-search - Azure 搜索规范化小写字段
- c# - 组合框作为控件模板传递,然后作为弹出窗口传递
- java - 带有 CompletableFuture 的 Java 运行循环