Click here to Skip to main content
14,694,079 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:

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.
Where is your question? Any problems?

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
string AllText = System.IO.File.ReadAllText(@"c:\temp.txt");
StringBuilder str = new StringBuilder(AllText);
str.Replace("Old Values","New Values");

private bool WriteToFile(string path, string content)
    if (!string.IsNullOrEmpty(path))
            using (StreamWriter sw = new StreamWriter(path))
            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.
Read your file word by word in an array, loop the array and find the word
and then replace the word.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900