StreamWriter用新文本替换行

Pyr*_*cer 5 c# forms windows streamwriter

是否有可能用新文本替换文本文件中的文本而不删除其他数据,这是我的示例代码,但它不起作用,我知道它有问题,但我无法弄清楚,谢谢,

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();

    }
Run Code Online (Sandbox Code Playgroud)

我想知道我是否使用正则表达式或直接替换线,

ppe*_*rov 16

你可以更容易地做到这一点:

        string[] lines = System.IO.File.ReadAllLines("test");
        lines[0] = /* replace with whatever you need */
        System.IO.File.WriteAllLines("test", lines);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助

int.TryParse如果你不希望在你的代码部分引发异常,我也建议使用,以防文件的第一行或文本框值不是数字

如果你真的想使用这个,你可以使用这个,也是一个更简单的方法:

line[0] = newbal.ToString();
foreach(string s in lines)
    sw.WriteLine(s);
Run Code Online (Sandbox Code Playgroud)