c#创建文​​件后无法写入文件

时间:2018-10-14 21:09:38

标签: c# file

我的问题真的很简单。我创建了一个文件,但无法写入。但是,如果我关闭程序,然后在创建文件时重新打开它,则不会引发任何异常。我认为当File.Create方法运行时,程序将其锁定。 path只是txt文件的位置。当我尝试手动删除文件时,它说我的程序正在使用它。

if (!File.Exists(path)) File.Create(path);

try
{
    File.WriteAllLines(path, new string[] {"hi"});
}
catch(IOException)
{
    Console.WriteLine(ex.ToString());
}

1 个答案:

答案 0 :(得分:3)

您不想要

File.Create(path);

由于它创建了FileStream,因此该文件具有排他锁。您只需要File.WriteAllLines

try
{
    File.WriteAllLines(path, new string[] {"hi"});
}
catch (IOException ex)
{
    Console.WriteLine(ex.ToString());
}

如果要确保创建path中的所有子目录,则应创建目录,而不是文件:

try
{
    Directory.CreateDirectory(Path.GetDirectoryName(path));

    File.WriteAllLines(path, new string[] {"hi"});
}
catch (IOException ex)
{
    Console.WriteLine(ex.ToString());
}