2

当我尝试这样做时:

Directory.CreateDirectory([folderPath]);
File.CreateText([folderPath]);

我有一个例外 -

System.UnauthorizedAccessException was unhandled by user code
  HResult=-2147024891
  Message=Access to the path 'C:\[folderPath]' is denied.
  Source=mscorlib
  StackTrace:
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
       at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
       at System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost)
       at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
       at System.IO.StreamWriter..ctor(String path, Boolean append)
       at System.IO.File.CreateText(String path)
       at Contest.Service.FileSystem.CreateFileAndFolderForAttempt(IAttempt attempt) in c:\Users\Mif\Documents\Visual Studio 2012\Projects\Contest\Contest.Service\FileSystem.cs:line 33
       at Contest.Service.Tests.FileSystemTests.TestCreateFileAndFolderForAttempt() in c:\Users\Mif\Documents\Visual Studio 2012\Projects\Contest\Contest.Service.Tests\UnitTest1.cs:line 32
  InnerException:

文件资源管理器向我展示:

属性:[三态/不确定复选框] 只读(仅适用于文件夹中的文件)

但是Debug.WriteLine(CurrentContestDirectory.Attributes.ToString()); 给我看 - Directory。而不是只读属性!

我在 Google 中寻找“使用 C# 删除目录上的只读属性”,但所有答案都对我没有帮助。我需要做什么?

所有代码都在我的本地计算机上运行 Windows 8。管理员帐户。如果我手动取消选中只读属性,在代码运行后它会切换回来。

这是简单的控制台应用程序。

现在我手动创建文件夹。默认情况下它是只读的。

cmd 中的 attrib -r C:\new /s 不起作用!!!

如果我手动取消选中只读并单击确定,那么如果我单击属性 -只读回来

4

3 回答 3

1

试试这个代码:

 Directory.CreateDirectory(@"c:\newfolder");
 File.CreateText(@"c:\newfolder\textfile.txt");
于 2012-11-13T01:53:40.277 回答
0

我将验证您运行此代码的应用程序本身在 Windows 中是否具有适当的权限。例如,右键单击应用程序并单击“以管理员身份运行”

于 2012-11-13T01:53:29.670 回答
0
File.CreateText([folderPath]);

可能是错的。当文件路径实际上是文件夹路径时,任何创建文件(或打开流)的尝试都将以

UnauthorizedAccessException

该例外非常具有误导性,并要求您查看所有错误的地方。去过,看过。

于 2014-01-23T21:11:14.797 回答