[英]c# , Winform application -search for specific line and replace it with other line
我有一個帶有按鈕的小型winform應用程序,單擊該按鈕時,我想在文本文件( file.txt
)中搜索特定單詞,然后用其他內容替換找到它的整個行。
假設我的文本文件是:
ohad yes no
box cat dog
etc...
我想搜索ohad,一旦找到它,就將行“ ohad yes no”替換為新行“是,我做到了”
因此txt文件為:
yes I did it
box cat dog
etc...
到目前為止,這是我的代碼:
string lineX;
StringBuilder sb = new StringBuilder();
using (System.IO.StreamReader file = new System.IO.StreamReader(textBox20.Text))
{
while ((lineX = file.ReadLine()) != null)
{
if (lineX.Contains("SRV"))
{
sb.AppendLine(lineX.ToString());
}
}
}
StreamReader streamReader;
streamReader = File.OpenText(textBox20.Text);
string contents = streamReader.ReadToEnd();
streamReader.Close();
StreamWriter streamWriter = File.CreateText(textBox20.Text);
streamWriter.Write(contents.Replace(sb.ToString(), textBox26.Text + textBox29.Text + textBox30.Text + textBox27.Text + textBox28.Text));
streamWriter.Close();
謝謝大家
轄
嘗試這個:
// Read file into a string array (NOTE: You should check if exists first!)
string[] Lines = File.ReadAllLines(textBox20.Text);
for(int i=0;i<Lines.Length;i++) {
if(Lines[i].Contains("SRV")) {
Lines[i] = "New value for line";
// if you only want to replace one line, uncomment the next row:
// break;
}
}
// Write array back to file
File.WriteAllLines(textBox20.Text, Lines);
對於初學者,如何遵循我提出的這些評論。
var s = @"
ohad yes no
box cat dog
";
//split string into array
//go through each item in array
//check if it contains "ohad"
//if so, replace that line with my text
//convert array to string
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.