HOW DO I LOCATE A PARTICULAR WORD IN A TEXT FILE

marcel ethan

Total Post:104

Points:728
Posted by  marcel ethan
 1075  View(s)
Ratings:
Rate this:

I am sending mails (in asp.net ,c#), having a template in text file (.txt) like below

User Name :<User Name>

Address : <Address>.

I used to replace the words within the angle brackets in the text file using the below code

StreamReader sr;

sr = File.OpenText(HttpContext.Current.Server.MapPath(txt));

copy = sr.ReadToEnd();

sr.Close(); //close the reader

copy = copy.Replace(word.ToUpper(),"#" + word.ToUpper()); //remove the word specified UC

//save new copy into existing text file

FileInfo newText = new FileInfo(HttpContext.Current.Server.MapPath(txt));

StreamWriter newCopy = newText.CreateText();

newCopy.WriteLine(copy);

newCopy.Write(newCopy.NewLine);

newCopy.Close();

Now I have a new problem,

the user will be adding new words within an angle, say for eg, they will be adding <Salary>.

In that case i have to read out and find the word <Salary>.

In other words, I have to find all the words, that are located with the angle brackets (<>).

How do I do that?

  1. Sumit Kesarwani

    Post:378

    Points:2694
    Re: How do I locate a particular word in a text file

    Hi, 

    You should place some of your objects into using blocks. Something like this:

    using(StreamReader sr =File.OpenText(HttpContext.Current.Server.MapPath(txt)))
    {
        copy =sr.ReadToEnd();
    } // reader is closed by the end of the using block
    //remove the word specified UC
    copy = copy.Replace(word.ToUpper(), "#" +word.ToUpper());   
    //save new copy into existing text file FileInfo newText = new FileInfo(HttpContext.Current.Server.MapPath(txt));
    using(var newCopy = newText.CreateText())
    {
        newCopy.WriteLine(copy);
        newCopy.Write(newCopy.NewLine);
    }

    The using block ensures that resources are cleaned up even if an exception is thrown.

      Modified On Apr-05-2018 04:27:54 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!