[英]How can I replace a word in a txt file in C#
我正在嘗試打開.txt文件,搜索一個單詞,然后在出現的任何地方都將其替換為另一個單詞。 我可以這樣做,但不能使用.txt文件,而只能使用我在.cs
文件中編寫的字符串。這是到目前為止的方法:
public void EditorialControl(string fileName, string word, string replacement)
{
List<string> list = new List<string>();
using (StreamReader reader = new StreamReader(directory + fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
list.Add(line);
}
reader.Close();
}
}
當我在Main()
調用方法時,它應該使用參數word
並將其替換為我選擇的替換單詞。
你們能幫我用代碼代替方法中的單詞嗎?
它比您想象的要簡單得多:
File.WriteAllText(fileName, File.ReadAllText(fileName).Replace(word1, word2));
就是這樣!
您可以使用regex
string target=System.IO.File.ReadAllText(directory + fileName);
Regex.Replace(target,@"\b"+word+@"\b",replacement);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.