关于使用csharp替换文件中的文本 [英] Regardingg replacing the text in file using csharp
问题描述
你好
我有一个文本文件,里面有一些单词或行.
我想通过在文本框中输入来搜索该文件中的特定单词
之后,我想用在文本框中输入的另一个单词替换该特定单词,然后单击按钮,它将在文本文件中替换该单词.
我已经完成了只搜索一行中的特定单词的工作,我无法为下一行进行搜索,并且我使用了替换功能,但它替代了文本文件中的整行而不是特定单词.
我正在WINDOWS FORMS中的CSharp中执行此操作.
hello
i have one text file which have some words or lines in it.
i want to search a paricular word in that file by entering in the textbox
After that i want to replace that particular word with another word entered in the textbox and by button click it should replace that word in the text file.
i have done for searching particular word in one line only i am not able to do serach for next line and also i used replace function but it is replacing entire lines in the text file instead of particular word.
i am doing this in CSharp in WINDOWS FORMS.
推荐答案
您可以尝试以下操作:
You can try this:
//Read a file as text:
string AllText = System.IO.File.ReadAllText(@"c:\temp\test1.txt");
string oldWord = "asd";
int oldWidth = oldWord.Length;
string newWord = "1234";
int i = AllText.IndexOf(oldWord);
while (i > -1)
{
AllText = AllText.Substring(0, i) + newWord + AllText.Substring(i + oldWidth);
i = AllText.IndexOf(oldWord, i);
}
//Do something with the result
Console.WriteLine(AllText);
string AllText = System.IO.File.ReadAllText(@"c:\temp.txt");
StringBuilder str = new StringBuilder(AllText);
str.Replace("Old Values","New Values");
this.WriteToFile(@"c:\temp.txt",str.ToString());
private bool WriteToFile(string path, string content)
{
if (!string.IsNullOrEmpty(path))
{
try
{
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine(content);
}
return true;
}
catch (Exception ex)
{
MessageBox.Show("Cant write in file...\n" + ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
}
return false;
}
尝试逐行将文件读取到字符串数组中,然后用在文本框中输入的单词替换该数组中的所有字符串.
Trying reading your file into a string array line by line and then replace all strings in this array with the word you have entered in your text box.
这篇关于关于使用csharp替换文件中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!