在 .NET 中使用 XmlWriter 写入只读文件

发布于 2024-10-31 13:13:03 字数 453 浏览 0 评论 0原文

我想使用 写入只读文件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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

提赋 2024-11-07 13:13:03

如果文件设置为只读,则需要重新设置标志,没有解决方法。

当然,您可以删除文件(这仍然需要您清除标志)并写入一个新文件,但是如果您的写入操作没有发生(某处例外),您就会丢失内容。

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.

墨落成白 2024-11-07 13:13:03

据我了解,鉴于该标志是由操作系统直接控制的,因此您必须删除只读标志才能写入文件。

如果您想要避免其他人在启用写入标志时写入该文件的可能性,您可以对该文件进行临时副本(具有写入权限),将 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文