如何使用StringBuilder写回文本文件?

时间:2015-01-06 03:55:26

标签: c#

目前我的代码没有插入其他数据,而是覆盖了我的测试文件中的数据。

代码片段如下:

string path = @"C:\\test.txt"; // <==NEW
StreamWriter sw = new StreamWriter(new FileStream(path, Filemode.Open, FileAccess.Write)); // <==NEW
StringBuilder Editions = new StringBuilder(400);



Editions.Insert(0, "0");
Editions.Insert(1, "0");
//Editions.Remove(9, 14);
//Editions.Insert(11, "R");
//Editions.Insert(12, "M");
//Editions.Insert(13, "A");
//Editions.Insert(14, "L");
//Editions.Insert(15, "L");
//Editions.Insert(16, " ");
//Editions.Insert(17, " ");
//Editions.Insert(18, " ");
//Editions.Insert(193, "C");
//Editions.Insert(194, "L");
sw.Write(Editions.ToString()); // <== NEW
sw.Flush(); // <== NEW
sw.Close(); // <== NEW

1 个答案:

答案 0 :(得分:1)

如果您需要添加更多数据,则需要以Append模式

打开文件
@"C:\\test.txt"; // <==NEW
StreamWriter sw = new StreamWriter(new FileStream(path, Filemode.Append, FileAccess.Write)); // <==NEW
StringBuilder Editions = new StringBuilder(400);


Editions.Insert(0, "0");
Editions.Insert(1, "0");
//Editions.Remove(9, 14);
//Editions.Insert(11, "R");
//Editions.Insert(12, "M");
//Editions.Insert(13, "A");
//Editions.Insert(14, "L");
//Editions.Insert(15, "L");
//Editions.Insert(16, " ");
//Editions.Insert(17, " ");
//Editions.Insert(18, " ");
//Editions.Insert(193, "C");
//Editions.Insert(194, "L");
sw.Write(Editions.ToString()); // <== NEW
sw.Flush(); // <== NEW
sw.Close(); // <== NEW

更多信息 - here

从MSDN引用:附加

  

打开文件(如果存在)并搜索到文件的末尾,或者   创建一个新文件。这需要FileIOPermissionAccess.Append   允许。 FileMode.Append只能与。一起使用   FileAccess.Write。试图在结束之前寻找一个位置   file抛出IOException异常,任何读取尝试都失败   并抛出NotSupportedException异常。

此外 - 当您使用Insert时,请注意&#34; ArgumentOutOfRangeException&#34; 。! READ