Home > DeveloperSection > Forums > How do I locate a particular word in a text file
marcel ethan
marcel ethan

Total Post:105

Points:735
Posted on    August-27-2014 1:59 AM

 ASP.Net
Ratings:


 1 Reply(s)
 633  View(s)
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?



Sumit Kesarwani

Total Post:378

Points:2694
Posted on    August-27-2014 11:19 PM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick