覆盖现有的XML文件(如果已存在) [英] Overwrite existing XML file if it alreadly exists
本文介绍了覆盖现有的XML文件(如果已存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试覆盖现有的xml文件(如果已经存在).
I am trying to overwrite an existing xml file if it already exists.
我正在使用下面的代码检查文件是否存在,然后将其覆盖.现有文件是隐藏的,因此在尝试覆盖之前我将其取消隐藏.
I am using the code below to check if the file exists and then overwrite it if it does. The existing file is hidden so I am unhiding it before attempting to overwrite.
文件未发生更改,但是覆盖不起作用.
The changes are not occuring to the file and the overwriting is not working however.
这是我在下面使用的代码减去编写新xml数据的部分.
Here is the code I am using below minus the part where I am writing the new xml data.
if(File.Exists(filePath))
{
File.SetAttributes(filePath,FileAttributes.Normal);
FileIOPermission filePermission =
new FileIOPermission(FileIOPermissionAccess.AllAccess,filePath);
FileStream fs = new FileStream(filePath, FileMode.Create);
XmlWriter w = XmlWriter.Create(fs);
}
推荐答案
尝试以这种方式写入文件:
Try writing to the file like this :
if(File.Exists(filePath))
{
File.SetAttributes(filePath,FileAttributes.Normal);
FileIOPermission filePermission =
new FileIOPermission(FileIOPermissionAccess.AllAccess,filePath);
using(FileStream fs = new FileStream(filePath, FileMode.Create))
{
using (XmlWriter w = XmlWriter.Create(fs))
{
w.WriteStartElement("book");
w.WriteElementString("price", "19.95");
w.WriteEndElement();
w.Flush();
}
}
}
这篇关于覆盖现有的XML文件(如果已存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文