我尝试在内存流中打开一个归档Xml文件(在zip文件中,但不是将其解压缩到物理目录中),然后对其进行更改并保存。但是归档xml文件不会被覆盖,相反,它会获得Xml数据的两个副本。一个拷贝是Xml数据的原始拷贝,另一个拷贝是同一存档文件中的Xml数据的更改/修改/编辑拷贝。这是我的代码,请帮助我用所做的更改覆盖现有的Xml数据,而不是在同一个归档Xml文件中有两个xml数据副本。
static void Main(string[] args)
{
string rootFolder = @"C:\Temp\MvcApplication5\MvcApplication5\Package1";
string archiveName = "MvcApplication5.zip";
string folderFullPath = Path.GetFullPath(rootFolder);
string archivePath = Path.Combine(folderFullPath, archiveName);
string fileName = "archive.xml";
using (ZipArchive zip = ZipFile.Open(archivePath, ZipArchiveMode.Update))
{
var archiveFile = zip.GetEntry(fileName);
if (archiveFile == null)
{
throw new ArgumentException(fileName, "not found in Zip");
}
if (archiveFile != null)
{
using (Stream stream = archiveFile.Open())
{
XDocument doc = XDocument.Load(stream);
IEnumerable<XElement> xElemAgent = doc.Descendants("application");
foreach(var node in xElemAgent)
{
if(node.Attribute("applicationPool").Value!=null)
{
node.Attribute("applicationPool").Value = "MyPool";
}
}
doc.Save(stream);
}
Console.WriteLine("Document saved");
}
}
}发布于 2015-04-09 04:13:24
首先从流中读取XML数据,然后将其写入指向文件末尾的同一个流。为了说明这一点,假设旧文件包含ABCD,我们希望用123替换它。
当前的方法将导致ABCD123,因为流指向ABCD中的最后一个字符。
如果在写入更改后的文件之前将流重置为位置0 (stream.Seek(0) ),则文件将包含123D,因为这不会减少文件长度。
解决方案是删除旧的ZipArchiveEntry并创建一个新的。
发布于 2018-04-20 09:00:21
我刚刚遇到了同样的问题,我通过添加第一行来解决它:
stream.SetLength(0);
xmlDoc.Save(stream);编辑:我看到你遇到了与你在上一个答案的评论中提到的相同的解决方案。您可以在自己的问题中添加答案。它会帮助像我这样的人:]
https://stackoverflow.com/questions/29524319
复制相似问题