25

我似乎无法弄清楚如何在不覆盖文件的情况下将数据写入文件。我知道我可以使用 File.appendtext 但我不确定如何将其插入我的语法中。这是我的代码:

TextWriter tsw = new StreamWriter(@"C:\Hello.txt");

//Writing text to the file.
tsw.WriteLine("Hello");

//Close the file.
tsw.Close();

我希望它每次运行程序时都写 Hello,而不是覆盖以前的文本文件。感谢您阅读本文。

4

9 回答 9

60

true 作为append构造函数的参数传递:

TextWriter tsw = new StreamWriter(@"C:\Hello.txt", true);
于 2011-04-01T17:42:03.837 回答
10

更改您的构造函数以将 true 作为第二个参数传递。

TextWriter tsw = new StreamWriter(@"C:\Hello.txt", true);
于 2011-04-01T17:42:15.303 回答
5

您必须打开,new StreamWriter(filename, true)以便它附加到文件而不是覆盖。

于 2011-04-01T17:42:09.903 回答
4

这是一段将值写入日志文件的代码。如果文件不存在,它会创建它,否则它只是附加到现有文件。您需要添加“使用 System.IO;” 在代码的顶部,如果它不存在的话。

string strLogText = "Some details you want to log.";

// Create a writer and open the file:
StreamWriter log;

if (!File.Exists("logfile.txt"))
{
  log = new StreamWriter("logfile.txt");
}
else
{
  log = File.AppendText("logfile.txt");
}

// Write to the file:
log.WriteLine(DateTime.Now);
log.WriteLine(strLogText);
log.WriteLine();

// Close the stream:
log.Close();
于 2013-04-04T11:31:58.227 回答
2

最好的是

File.AppendAllText("c:\\file.txt","Your Text");
于 2011-04-01T17:51:33.247 回答
1

查看 File 类。

您可以使用

StreamWriter sw = File.Create(....) 

您可以打开现有文件

File.Open(...)

您可以轻松地附加文本

File.AppendAllText(...);
于 2011-04-01T17:53:00.487 回答
1

首先检查文件名是否已经存在,如果是,则创建一个文件并同时关闭它,然后使用AppendAllText. 有关更多信息,请查看下面的代码。


string FILE_NAME = "Log" + System.DateTime.Now.Ticks.ToString() + "." + "txt"; 
string str_Path = HostingEnvironment.ApplicationPhysicalPath + ("Log") + "\\" +FILE_NAME;


 if (!File.Exists(str_Path))
 {
     File.Create(str_Path).Close();
    File.AppendAllText(str_Path, jsonStream + Environment.NewLine);

 }
 else if (File.Exists(str_Path))
 {

     File.AppendAllText(str_Path, jsonStream + Environment.NewLine);

 }
于 2018-08-16T10:26:13.760 回答
0
using (StreamWriter writer = File.AppendText(LoggingPath))
{
    writer.WriteLine("Text");
}
于 2011-04-01T17:43:25.847 回答
0

以上都不起作用我自己找到了解决方案

 using (StreamWriter wri = File.AppendText("clients.txt"))
        {
            wri.WriteLine(eponimia_txt.Text + "," + epaggelma_txt.Text + "," + doy_txt.Text + "," + dieuthini_txt.Text + ","
                + proorismos_txt.Text + "," + poly_txt.Text + "," + sxePara_txt.Text + "," + afm_txt.Text + ","
                + toposFortosis_txt.Text + ",");
        }
于 2021-03-15T19:37:02.647 回答