Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.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#中覆盖文件_C#_C# 4.0 - Fatal编程技术网

使用流编写器在c#中覆盖文件

使用流编写器在c#中覆盖文件,c#,c#-4.0,C#,C# 4.0,我正在尝试使用c#中的stream writer编写html文件,如果关闭应用程序并再次运行,它将覆盖该文件,但当我尝试在不关闭应用程序的情况下为不同场景编写文件时,它会追加。我想在第二种情况下也覆盖它 using (FileStream fs = new FileStream("Report.html", FileMode.Create, FileAccess.Write)) { using (StreamWriter w = new StreamWr

我正在尝试使用c#中的stream writer编写html文件,如果关闭应用程序并再次运行,它将覆盖该文件,但当我尝试在不关闭应用程序的情况下为不同场景编写文件时,它会追加。我想在第二种情况下也覆盖它

using (FileStream fs = new FileStream("Report.html", FileMode.Create, FileAccess.Write))                 
{
    using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
    {                               
        w.WriteLine(html); 
    }
}

要附加到文件末尾,请执行以下操作:

File.AppendAllText("Report.html", html, Encoding.UTF8);
File.WriteAllText("Report.html", html, Encoding.UTF8);
要覆盖您的文件,请执行以下操作:

File.AppendAllText("Report.html", html, Encoding.UTF8);
File.WriteAllText("Report.html", html, Encoding.UTF8);

尝试显式关闭写入程序和流,而不是依赖于您使用()表达式来完成此操作。

FileMode.Create会覆盖现有文件,而不是附加到现有文件。您应该显示导致追加的代码。(还要确保您没有附加到
html
使用
是不可靠的?没有,但他没有显示要附加的代码,我怀疑是因为他试图在同一个using表达式中重复使用流。只要你理解其中的含义,使用表达式就非常有效。