![](/img/trans.png)
[英]I'm creating docx file in c# using Docx library. when i click create button its not overwrite the document. it repeated display. how i can do that
[英]How do I overwrite a DOCX XML file with C#?
我被卡住了。 目標是僅當相應的date屬性在給定日期之后,才使用C#工具更改MS Word跟蹤更改中的審閱者姓名。 變量字符串docPath
傳遞給方法changeRevAuthor
。 docPath
代表打開的DOCX文件。 傳遞文件時必須將其打開,因為該工具還會在運行該方法之前將所有DOC文件保存為DOCX。
作者姓名被更改,並且XML文件中的日期已正確確認。 我們通過將XML保存到靜態路徑進行了測試。 但是,我需要做的實際上是覆蓋現有的XML文件,而不是將其拉出並保存到其他位置。 這是現有方法:
private void changeRevAuthor(string docPath)
{
using (Stream stream = System.IO.File.Open(docPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
stream.Seek(0, SeekOrigin.End);
XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
WordprocessingDocument document = WordprocessingDocument.Open(stream, false);
XDocument mainDocumentXDoc = document.MainDocumentPart.GetXDocument();
var nodes = mainDocumentXDoc.Descendants().Where(x => x.Attributes(w + "author").Count() > 0);
var currentdate = "2016-06-21";
foreach (XElement node in nodes)
{
var date = node.Attribute(w + "date").ToString().Substring(8, 10);
if (DateTime.Parse(date) < DateTime.Parse(currentdate))
{
node.SetAttributeValue(w + "author", "LUZ");
Debug.WriteLine(date);
}
}
mainDocumentXDoc.Save(document.MainDocumentPart.GetStream(FileMode.Create));
}
}
通過研究,我相信最后一行應該可以解決問題: mainDocumentXDoc.Save(document.MainDocumentPart.GetStream(FileMode.Create));
但是,這將返回以下錯誤:
在System.IO.Packaging.dll中發生“類型為'System.IO.IOException的未處理的異常'。 。”
當我將其更改為FileAccess.Write
或FileAccess.ReadWrite
,收到以下錯誤:
'其他信息:該進程無法訪問文件'C:\\ Users .... \\ Desktop \\ C#Test \\ Results \\ newtest.docx',因為該文件正在被另一個進程使用。'
我從這里去哪里?
謝謝盧克
這可以解決您的問題:
void changeRevAuthor (string docPath)
{
XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
WordprocessingDocument document = WordprocessingDocument.Open(docPath, true);
XDocument mainDocumentXDoc = document.MainDocumentPart.GetXDocument();
var nodes = mainDocumentXDoc.Descendants().Where(x => x.Attributes(w + "author").Count() > 0);
foreach (XElement node in nodes)
{
// ...
node.SetAttributeValue(w + "author", "LUZ");
}
mainDocumentXDoc.Save(document.MainDocumentPart.GetStream(FileMode.Create));
}
但不完整 。
您還應該修改word \\ comments和docProps \\ core軟件包部分,而不僅限於word \\ document 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.