使用File.Create()后由另一个进程使用的文件

Bre*_*ett 110 c# file-io

我正在尝试检测运行时是否存在文件,如果没有,则创建它.但是当我尝试写入时,我收到此错误:

该进程无法访问文件'myfile.ext',因为它正由另一个进程使用.

string filePath = string.Format(@"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
if (!File.Exists(filePath)) 
{ 
    File.Create(filePath); 
} 

using (StreamWriter sw = File.AppendText(filePath)) 
{ 
    //write my text 
}
Run Code Online (Sandbox Code Playgroud)

关于如何修复它的任何想法?

Car*_*tes 133

    File.Create(FilePath).Close();
    File.WriteAllText(FileText);
Run Code Online (Sandbox Code Playgroud)

我想更新这个答案,说这不是写入所有文本的最有效方法.如果您需要快速和脏的东西,您应该只使用此代码.

当我回答这个问题时,我还是一个年轻的程序员,那时我觉得我有点天才想出这个答案.

  • 这段代码的缺点是它不必要地打开文件两次.此外,根本不需要检查文件是否存在,因为如果FileStream构造函数不存在,它将自动为您创建它,除非您明确告诉它不要这样做. (13认同)
  • 这很有用. (4认同)
  • 我喜欢所有其他答案都太复杂了.人们没有意识到每个问题都有一个更简单的答案. (4认同)
  • @reirab这完全是相对的.我需要检查文件是否存在,如果存在,删除它并再次创建它,所以在我的情况下这个答案是首选. (2认同)
  • 这个答案的重点是表明您可以只在最后添加`.Close()`,因此在任何情况下都可以使用。我不信任对所有内容都使用`FileStream`的系统,因为我不希望在`FileMode.Create`上发生该文件已经存在的异常-特别是当我想清除内容而不是通过`FileMode附加到它们时打开 对我来说,`FileStream`只有在删除了有问题的文件然后写入它之后才真正起作用。由于`File.Create`使其保持打开和锁定状态,因此似乎在其中添加`.Close()`是处理我的方案和SO的唯一真实方法。 (2认同)

Chr*_*way 108

File.Create方法创建文件并在文件上打开FileStream.所以你的文件已经打开了.你根本不需要file.Create方法:

string filePath = @"c:\somefilename.txt";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
    //write to the file
}
Run Code Online (Sandbox Code Playgroud)

StreamWriter如果文件存在,构造函数中的布尔值将导致附加内容.


Ral*_*ine 25

创建文本文件时,您可以使用以下代码:

System.IO.File.WriteAllText("c:\test.txt", "all of your content here");
Run Code Online (Sandbox Code Playgroud)

使用评论中的代码.必须关闭您创建的文件(流).File.Create将文件流返回到刚刚创建的文件:

string filePath = "filepath here";
if (!System.IO.File.Exists(filePath))
{
    System.IO.FileStream f = System.IO.File.Create(filePath);
    f.Close();
}
using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath))
{ 
    //write my text 
}
Run Code Online (Sandbox Code Playgroud)


小智 16

FileStream fs= File.Create(ConfigurationManager.AppSettings["file"]);
fs.Close();
Run Code Online (Sandbox Code Playgroud)

  • 欢迎来到Stackoverflow.您至少应该写简短的描述来描述您的答案/解决方案. (6认同)

小智 9

File.Create返回FileStream.您需要在写入文件时关闭它:

using (FileStream fs = File.Create(path, 1024)) 
        {
            Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
            // Add some information to the file.
            fs.Write(info, 0, info.Length);
        }
Run Code Online (Sandbox Code Playgroud)

您可以使用use来自动关闭文件.


Han*_*ant 8

我使用代码段更新了您的问题.在适当缩进之后,立即清楚问题是什么:您使用File.Create()但不关闭FileStream它返回的内容.

这样做是不必要的,StreamWriter已经允许附加到现有文件创建新文件(如果它尚不存在).像这样:

  string filePath = string.Format(@"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
  using (StreamWriter sw = new StreamWriter(filePath, true)) {
    //write my text 
  }
Run Code Online (Sandbox Code Playgroud)

哪个使用这个StreamWriter构造函数.