Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#can';创建文件后,无法写入该文件_C#_File - Fatal编程技术网

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.Remove
File.Create(路径):您不希望创建
FileStream
文件(这会对文件设置独占锁定)。WriteAllines创建、打开和写入行,并关闭文件。删除文件。创建。