0

I am using C# in Microsoft Visual Studio 2012, I am working on the following code:

 string source =  "d:\\source.txt";
 string newFile = "d:\\newFile.txt"; 
 if(!File.Exists(newFile))
 {
      File.Create(newFile);
      string content = File.ReadAllText(source);
      File.AppendAllText(newFile,content);
 }

This code successfully creates the File but when it compiles the File.AppendAllText(newFile,content) it generates the error:

the process cannot access the file "d:\newFile.txt" because it is being used by another process.

Why would this be?

4

2 回答 2

6

File.Create方法返回一个FileStream对象。这是保持文件打开以供写入。在该对象关闭之前,无法写入该文件。解决此问题的最佳方法是简单地关闭返回的文件

File.Create(newFile).Close();

此代码本质上是将现有文件的内容复制到新文件中。已经有一个 API 可以做到这一点:File.Copy. 您的代码可以简化为以下

try { 
  File.Copy(source, newFile);
} catch (Exception) { 
  // File already exists or write can't occur 
}
于 2013-08-30T04:17:19.937 回答
0

你不需要创建文件,AppendAllText如果不存在就创建,你会得到异常,因为 File.Create 返回打开的文件流,然后你尝试再次访问同一个文件。您需要在访问同一文件之前正确关闭该流。

 string source =  "d:\\source.txt";
 string newFile = "d:\\newFile.txt"; 
 if(!File.Exists(newFile))
 {
      File.AppendAllText(newFile,File.ReadAllText(source););
 }

File.AppendAllText:

打开文件,将指定的字符串附加到文件,然后关闭文件。如果文件不存在,此方法创建一个文件,将指定的字符串写入文件,然后关闭文件。

但你可以简单地通过一行来完成你的任务

File.Copy(source , newFile , false);
于 2013-08-30T04:21:55.130 回答