Is it possible to replace the text in a text file with a new text without erasing the other data, here is my sample code, but its not working, I know there's a problem with it but I can't figure out, thanks,
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....
Your 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();
}
I'm wondering if I use the Regex or directly replace the line,
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…