在c中创建一个文件和一个文件夹#

问题描述:

我想在用户文件夹中创建一个文件并用一些基本文本填充它。看似简单,但我不断收到一个错误:在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

有一对夫妇,我看到了手说可以会造成麻烦的错误...

首先,而不是使用网络/文件夹分隔符,使用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

这里有些东西可能会有所帮助 - 为了让它更容易一些,我没有包含创建文件或文件夹的代码,只是为了获取现有文件,打开并写入文件。

希望这给了一些方向,你可以从那里去。

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(); 
     } 

    } 

有一点需要注意:确保您对您想要写入的文件夹和文件具有权限。