【发布时间】:2013-01-10 02:37:21
【问题描述】:
是否可以在不删除其他数据的情况下用新文本替换文本文件中的文本,这是我的示例代码,但它不起作用,我知道它有问题但我无法弄清楚,谢谢,
private void button1_Click_1(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("test10101.txt");
List<string> lines = new List<string>();
while (!sr.EndOfStream)
lines.Add(sr.ReadLine());
output = Convert.ToInt32(textBox1.Text);
newbal = Convert.ToInt32(lines[0]) - output;
MessageBox.Show("Please get your cash....\n\nYour new balance is: $" + newbal);
sr.Close();
{
string linetoreplace = lines[0];
int newlinevalue = newbal;
string contents = sr.ReadToEnd();
StreamWriter sw = new StreamWriter("test10101.txt" + ".tmp");
//contents = Regex.Replace(contents, linetoreplace, newlinevalue.ToString());
contents = contents.Replace(linetoreplace, newlinevalue.ToString());
sw.WriteLine(contents);
sw.Close();
}
我想知道我是使用正则表达式还是直接替换该行,
【问题讨论】:
-
请不要将你的问题标题与标签堆叠起来,这不是必需的。
-
它不起作用是对问题的非常糟糕的解释。请从示例中删除不相关的代码,并添加有关您看到的错误/行为的详细信息。
-
问题是,我需要制作一个使用streamwriter和streamreader的程序,只使用1个文本文件,但问题是,如果我使用writeline,所有的文本文件都会被替换,我只需要单行被替换。那里的错误,它没有写入任何数据,你能帮我解决我的问题吗?谢谢
-
你的
contents变量不是空的吗?您正在关闭流读取器,然后调用ReadToEnd,即使您不关闭它,我认为流位置此时将位于文件的末尾,因为您之前使用相同的流读取器来读取整个文件
标签: c# windows forms streamwriter