Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
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.
Posted
Comments
Sergey Alexandrovich Kryukov 4-Jun-11 0:37am    
Where is your question? Any problems?
--SA

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());

C#
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;
}
 
Share this answer
 
Read your file word by word in an array, loop the array and find the word
and then replace the word.
 
Share this answer
 
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);
 
Share this answer
 
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.
 
Share this answer
 

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