2012-06-09 37 views
1

就像tittle说的那样,我想在文件底部添加一个新字符串,但不知何故,它不起作用。 希望有人能帮助我x___x将新字符串添加到文件的最后一行

 private string add(string asd){ 
     {string filename = "asd.txt"; 
     StreamReader reader = new StreamReader(filename); 
     StreamWriter write = new StreamWriter(filename); 
     string input = null; 
     while ((input = reader.ReadLine()) != null) 
     { 
      write.WriteLine(input); 
     } 
     reader.Close(); 
     write.WriteLine(asd); 
     write.Close();} 

回答

6

使用File.AppendAllText

打开文件,将指定的字符串追加到文件中,然后关闭文件。如果该文件不存在,则此方法将创建一个文件,将指定的字符串写入该文件,然后关闭该文件。

例子:

private string Add(string asd) { 
    string filename = "asd.txt"; 
    File.AppendAllText(filename, asd); 
} 
+0

+1很好的例子,但值得一提的是,File.AppendAllText不是线程安全的。 –

2

你写了/在同一时间从同一文件读取。这是行不通的。你将不得不创建一个临时文件来写入。

1

什么是这样的:

private string add(string asd){ 
{ 
     string filename = "asd.txt"; 
     string readText = File.ReadAllText(filename); 
     File.WriteAllText(filename , createText + asd); 
} 
相关问题