windows File.WriteAllText 抛出 UnauthorizedAccessException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1526393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:14:33  来源:igfitidea点击:

File.WriteAllText throws UnauthorizedAccessException

.netwindowsfile-access

提问by ripper234

Doing File.WriteAllTextto a remote path throws UnauthorizedAccessException. When I open the file in notepad I can edit it without a problem. The process that's trying to modify the file is running as my own user account, so it should be able to access it.

否则File.WriteAllText到远程路径抛出UnauthorizedAccessException。当我在记事本中打开文件时,我可以毫无问题地编辑它。尝试修改文件的进程正在以我自己的用户帐户运行,因此它应该能够访问它。

回答by Jay Riggs

According to MSDN, UnauthorizedAccessExceptioncan also be caused by:

根据MSDNUnauthorizedAccessException也可能由以下原因引起:

path specified a file that is read-only.

-or- 

This operation is not supported on the current platform.

-or- 

path specified a directory.
path specified a file that is read-only.

-or- 

This operation is not supported on the current platform.

-or- 

path specified a directory.

Is it possible one of these conditions is the cause of your problem?

这些情况之一是否可能是您的问题的原因?

回答by Roman Starkov

The UnauthorizedAccessExceptionis also thrown if the file has the "hidden" attribute set. Don't ask me why...

UnauthorizedAccessException如果该文件具有“隐藏”属性设置也抛出。不要问我为什么...

回答by Reed Copsey

I believe you also get this exception (although its not documented) if the file is being locked by another process or thread.

我相信如果文件被另一个进程或线程锁定,你也会得到这个异常(虽然它没有记录)。

Make sure nothing else has opened the file in a manner that prohibits writing. Notepad is not a good test for seeing if a file is locked, since it will open a locked file (ie: read-only files are fine).

确保没有其他任何东西以禁止写入的方式打开文件。记事本不是查看文件是否被锁定的好测试,因为它会打开一个锁定的文件(即:只读文件很好)。