c#can';创建文件后,无法写入该文件
我的问题很简单。我创建了一个文件,但无法写入。但是如果我关闭程序,然后在创建文件时重新打开,它不会抛出任何异常。我认为当c#can';创建文件后,无法写入该文件,c#,file,C#,File,我的问题很简单。我创建了一个文件,但无法写入。但是如果我关闭程序,然后在创建文件时重新打开,它不会抛出任何异常。我认为当File.Create方法运行时,程序会锁定它。 path只是一个txt文件的位置。当我试图手动删除文件时,它会显示我的程序正在使用它 if (!File.Exists(path)) File.Create(path); try { File.WriteAllLines(path, new string[] {"hi"}); } catch(IOException)
File.Create
方法运行时,程序会锁定它。
path
只是一个txt文件的位置。当我试图手动删除文件时,它会显示我的程序正在使用它
if (!File.Exists(path)) File.Create(path);
try
{
File.WriteAllLines(path, new string[] {"hi"});
}
catch(IOException)
{
Console.WriteLine(ex.ToString());
}
你不想
File.Create(path);
因为它创建了FileStream
,在文件上设置了一个exlusive锁。您只需要文件。writeAllines
:
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());
}
你不想
File.Create(path);
因为它创建了FileStream
,在文件上设置了一个exlusive锁。您只需要文件。writeAllines
:
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());
}
删除
File.Create(路径)代码>:您不希望创建FileStream
文件(这会对文件设置独占锁定)。WriteAllines创建、打开和写入行,并关闭文件。Remove File.Create.RemoveFile.Create(路径)代码>:您不希望创建FileStream
文件(这会对文件设置独占锁定)。WriteAllines创建、打开和写入行,并关闭文件。删除文件。创建。