2013-04-05 165 views
1

我想在用戶文件夾中創建一個文件並用一些基本文本填充它。看似簡單,但我不斷收到一個錯誤:在c中創建一個文件和一個文件夾#

Could not find a part of the path 'C:\websites\admin\upload\users\testuserID\testuserIDSampleRecord.txt'."} System.Exception {System.IO.DirectoryNotFoundException}

我的網站位於:c:\websites\testsite\,所以完整的路徑應該是:

c:/websites/testsite/admin/upload/users/ 

的IIS本地主機設置爲指向c:/websites/所以當我運行它,我鍵入localhost/testsite得到它

這裏是我有:

try 
      { 
      string SampleCaseText = BuildTextRecord(); 
      string username = (string)Session["userid"]; 
      string folderPath = "/testsite/admin/upload/users/" + username; 
      bool IsExists = System.IO.Directory.Exists(Server.MapPath(folderPath)); 

      if(!IsExists) 
       System.IO.Directory.CreateDirectory(Server.MapPath(folderPath)); 

      System.IO.File.Create(folderPath + "/" + username + "SampleRecord.txt"); 


      File.WriteAllText(Path.Combine(folderPath, username + "SampleRecord.txt"), SampleCaseText); 


      } 

它在正確的位置創建了新文件夾testuserID,但嘗試創建/寫入文件時失敗。

+1

嘗試使用'System.Path.CombinePath'函數,而不是字符串連接。另外,我認爲對'System.IO.File.Create'的調用應該使用Windows而不是web'/' – freefaller 2013-04-05 15:46:48

+0

你得到的錯誤是什麼? – Arshad 2013-04-05 15:48:09

+0

訪問權限怎麼樣?你可以檢查是否創建文件夾通過Windows資源管理器進入目錄? – Yahya 2013-04-05 15:48:16

回答

1

有一對夫婦,我看到了手說可以會造成麻煩的錯誤...

首先,而不是使用網絡/文件夾分隔符,使用Windows \一個來代替。

其次,你沒有在你應該使用的所有位置使用Server.MapPath ...導致使用web相對路徑而不是本地windows路徑。

嘗試這樣的事情,在那裏我已經將文件夾轉換爲在啓動Windows路徑,並把轉換userFilename到它自己的變量,並且使用的,而不是...

string folderPath = Server.MapPath("/testsite/admin/upload/users/" + username); 
bool IsExists = System.IO.Directory.Exists(folderPath); 
if(!IsExists) 
    System.IO.Directory.CreateDirectory(folderPath); 

string userFilename = Path.Combine(folderPath, username + "SampleRecord.txt"); 
System.IO.File.Create(userFilename); 
File.WriteAllText(userFilename, SampleCaseText); 
+0

謝謝!那裏almot。現在我得到:System.IO.IOException:進程無法訪問文件'C:\網站\ testwebsite \ admin \ upload \ users \ testUser \ testUserSampleRecord.txt',因爲它正在被另一個進程使用。 – 2013-04-05 17:10:18

0

這裏有些東西可能會有所幫助 - 爲了讓它更容易一些,我沒有包含創建文件或文件夾的代碼,只是爲了獲取現有文件,打開並寫入文件。

希望這給了一些方向,你可以從那裏去。

private void Error(string error) 
    { 
     var dir= new DirectoryInfo(@"yourpathhere"); 
     var fi = new FileInfo(Path.Combine(dir.FullName, "errors.txt")); 

     using (FileStream fs = fi.OpenWrite()) 
     { 
      StreamWriter sw = new StreamWriter(fs); 
      sw.Write(error); 
      sw.Close(); 
      sw.Dispose(); 
     } 

    } 

有一點需要注意:確保您對您想要寫入的文件夾和文件具有權限。