在 .NET 中使用 XmlWriter 写入只读文件
我想使用 写入只读文件XmlWriter
。执行此操作的正确方法是什么?
目前我有:
XmlWriterSettings lSettings = new XmlWriterSettings();
lSettings.Encoding = new UTF8Encoding(false);
lSettings.Indent = true;
XmlWriter lWriter = XmlWriter.Create(lPath, lSettings);
lXml.WriteContentTo(lWriter);
lWriter.Close();
我想知道是否有办法避免清除和重新设置只读标志。
I would like to write to a read-only file using XmlWriter
. What is the proper way to do this?
Currently I have:
XmlWriterSettings lSettings = new XmlWriterSettings();
lSettings.Encoding = new UTF8Encoding(false);
lSettings.Indent = true;
XmlWriter lWriter = XmlWriter.Create(lPath, lSettings);
lXml.WriteContentTo(lWriter);
lWriter.Close();
I'm wondering if there's a way to avoid clearing and re-setting the read-only flag.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果文件设置为只读,则需要重新设置标志,没有解决方法。
当然,您可以删除文件(这仍然需要您清除标志)并写入一个新文件,但是如果您的写入操作没有发生(某处例外),您就会丢失内容。
If a file is set as read-only, you do need to re-set the flag, no workarounds.
Of course, you could delete the file (which still requires you to clear the flag) and write a new one, but then risk that if your write operation doesn't happen (exception somewhere), you lose the contents.
据我了解,鉴于该标志是由操作系统直接控制的,因此您必须删除只读标志才能写入文件。
如果您想要避免其他人在启用写入标志时写入该文件的可能性,您可以对该文件进行临时副本(具有写入权限),将 XML 写入该文件,最后替换原始文件文件与您的文件并将标志设置为只读。
As I understand it you must remove the read-only flag to write to a file given the fact that this flag is controlled directly by the operating system.
If what you want is avoid the possibility that someone else can write to the file in the time the write flag is enabled you can do a temporary copy of the file (with write permissions), write your XML to that file and finally replace the original file with yours and set the flag to read-only.