无法从新创建的.txt中读取.它被另一个进程使用

rad*_*byx 0 c# file-io file visual-studio-2010

当我创建我log.txtFile.Create(Path.Combine(PATH, NAME));并然后尝试从中读取时,我得到一个例外:{System.IO.IOException: The process cannot access the file 'c:\temp\log.txt' because it is being used by another process..

如果log.txt文件退出而不是在方法中创建,我可以读取和写入日志而不会出现任何问题.

是否log.txt创建了异步,问题是程序在创建之前是否尝试读取它?

public static void WriteToLog(string text)
{
    try
    {
        if (!Directory.Exists(PATH))
        {
            Directory.CreateDirectory(PATH);
        }

        if( !File.Exists(Path.Combine(PATH, NAME)) )
        {
            File.Create(Path.Combine(PATH, NAME));
        }

        var logLines = File.ReadAllLines(Path.Combine(PATH, NAME)).ToList<string>();
        logLines.Insert(0, "-------------------------------------------------End New Log");
        logLines.Insert(0, text);
        logLines.Insert(0, "-------------------------------------------------Start New Log");
        File.WriteAllLines(Path.Combine(PATH, NAME), logLines);
    }
    catch (Exception ex)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

use*_*107 6

File.Create创建一个文件流,在创建后打开.所以该文件由其自己的进程使用.

只需将其更改为

        using(var f = File.Create(Path.Combine(PATH, NAME))) { } ;
Run Code Online (Sandbox Code Playgroud)