[英]StreamWriter replace line with a new text
是否有可能用新文本替換文本文件中的文本而不刪除其他數據,這是我的示例代碼,但它不起作用,我知道它有問題,但我無法弄清楚,謝謝,
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();
}
我想知道我是否使用正則表達式或直接替換線,
你可以更容易地做到這一點:
string[] lines = System.IO.File.ReadAllLines("test");
lines[0] = /* replace with whatever you need */
System.IO.File.WriteAllLines("test", lines);
希望這可以幫助
如果你不希望在你的代碼部分引發異常,我也建議使用int.TryParse
,以防文件的第一行或文本框值不是數字
如果你真的想使用這個,你可以使用這個,也是一個更簡單的方法:
line[0] = newbal.ToString();
foreach(string s in lines)
sw.WriteLine(s);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.