该进程无法访问该文件,因为它正被另一个进程错误使用

-3 c# file-io file

这是我的代码:

public static bool createFile(string dir) {
        dir="c:\\e.bat";
        System.IO.File.Create(dir);


            if (System.IO.File.Exists(dir))
            {
                try
                {
                    StreamWriter SW;
                    SW = System.IO.File.CreateText(dir);
                    SW.WriteLine("something ");
                    SW.Close();
                }
                catch (Exception e)
                {
                    Console.Write(e.Message);
                    Console.ReadLine();
                    return false;
                }                    
            }
            return true;            
    }
Run Code Online (Sandbox Code Playgroud)

这里dir是当前目录.我正面临错误进程无法访问该文件,因为它被另一个进程使用.我可以解决这个问题吗?

Jon*_*eet 10

你正在调用File.Create方法的开头 - 这会返回一个保持打开状态的流.目前尚不清楚你为什么要打电话,但我建议你删除那条线.

您还应该使用using语句,仅捕获特定的异常,使用适当的using指令,并遵循.NET命名约定.例如:

using System.IO;

...

public static bool CreateFile(string file)
{
    using (var writer = File.CreateText(file))
    {
        try
        {
            writer.WriteLine("something ");
        }
        catch (IOException e)
        {
            // TODO: Change the handling of this. It's weird at the moment
            Console.Write(e.Message);
            Console.ReadLine();
            return false;
        }
    }
    return true;            
}
Run Code Online (Sandbox Code Playgroud)

我已经删除了现有文件的检查,与前面的代码将永远存在,因为你只是创建它.

您还应该考虑使用File.WriteAllText更简单的方式来编写文件.