C# File.使用 FileMode.Create 打开只读文件
我想要做的是覆盖只读文件。具有读/写文件。
对于读/写文件,如果我使用 File.Open(file, FileMode.Create) ,那么如果文件存在,则将其删除并创建一个新文件。 (尽管我怀疑如果它存在,那么它只是打开文件并删除内容,这就是为什么它无法处理它遇到的读/写文件)。
我尝试过不同的 FileAccess 枚举,但它们似乎都没有帮助我(我不断收到 UnauthorizedAccessException )。
解决方法是,我只是在尝试 File.Open
并创建一个新文件之前将文件设置为读/写,这是执行此操作的唯一方法吗?
谢谢
What I want to do is overwrite a read-only file. With a read/write file.
With read/write files if I use File.Open(file, FileMode.Create)
then if the file exists then it is deleted and a new one is created. (Although I suspect that if it exists then it just opens the file and removes the contents, which is why it is unable to cope with files it encounters as read/write).
I have tried with different FileAccess
enums, but none of them seem to help me (I keep getting a UnauthorizedAccessException
).
The work around is that I just set the file as read/write before I try to File.Open
and make a new file, is this the only way to do this?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
考虑
ReadOnly
的目的。这是为了停止对文件的更改。您想要做的是更改文件(在本例中是覆盖它)。我想您需要做的是设置文件属性:
在写入文件之前。
Consider the purpose of
ReadOnly
. It's to stop alterations to the file. What you're trying to do, is alter the file (in this case by overwriting it).What I would imagine you would need to do, is set the file attribute:
Before you write to the file.
是的,这是设计使然的行为。您无法写入只读文件,因此也无法覆盖它。
因此,唯一且完全有效的选择是首先删除 ReadOnly 标志。
Yes, this is a by design behavior. You can't write into a file that is readonly, thus you can't overwrite it either.
So the only and perfectly valid option is to remove the ReadOnly flag first.
使用 FileInfo 将文件的属性从只读更改为只读(如果您有权限),然后覆盖该文件。
Use FileInfo to change attributes of the file from ReadOnly (if you have permissions) and then overwrite the file.
是的,您需要在写入之前删除只读属性。这里有一些文件实用程序来检测文件是否为只读,然后设置非只读属性。
Yes, you need to remove the readonly attribute before writing it. Here there are some file utils to detect if a file is readonly and then to set non-readonly attribute.