2012-11-13 26 views
1

當我嘗試這樣做:在C#創建目錄,而不只讀屬性

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管理員帳戶。如果我手動取消只讀attrinute,在代碼運行後切換回來。

這是簡單的控制檯應用程序。

現在我手動創建文件夾。它默認只讀。

attrib -r C:\新/ s在cmd不工作!

如果我取消選中手動只讀並單擊確定,然後如果我點擊屬性 - 只讀回來

+0

也許這隻讀屬性是從一些父文件夾繼承? –

+0

它直接在驅動器根目錄下。我不知道如何設置「C:\」不是隻讀。 – mif

+1

Web/Windows應用程序?也許這不是一個「只讀問題」,而是「權利問題不足」? – walther

回答

0

我會驗證運行此代碼本身在Windows正當權益您的應用程序。例如,用鼠標右鍵單擊該應用程序,然後單擊「以管理員身份運行」

+0

我的Visual Studio使用管理員權限運行。但是,如果我以管理員身份運行ConsoleApplication.exe,則會引發異常。 – mif

1

嘗試使用此代碼:

Directory.CreateDirectory(@"c:\newfolder"); 
File.CreateText(@"c:\newfolder\textfile.txt"); 
+0

我自己的代碼(沒有模板[folderPath])是一樣的。 – mif

+0

您在兩行代碼中都使用了[folderPath],請確保您的第二行:「File.CreateText」指向一個文件,如「file.txt」 –

0
File.CreateText([folderPath]); 

可能是錯誤的。任何試圖創建一個文件(或打開一個流)時的文件路徑實際上是一個文件夾路徑將與

UnauthorizedAccessException 

結束的例外是非常誤導,並要求你在錯誤的地方尋找。在那裏,看到它。