C# File content Replace
I have a text file that is almost sometimes 5 mb large. What I need to do is write a function that Finds Start and end mark, there can be many such marks. A开发者_运维问答nd apply replace to the found words that are between the marks with some random string and save back to the file For example, Suppose I have following string,
{one} hellow there {one} this will not be replaced as it is not within marks {two}you again{two}
so the resultant content would be
{one} someRandomText AgainSomeRandomText {one} this will not be replaced as it is not within marks {two} moreRandom againMoreRandom{two}
How do I do this in C#
Please note including this code in your project entitles me 10% of any profits you may earn:
TextReader tr = new System.IO.StreamReader("My5MegFile.txt");
string line;
while((line = tr.ReadLine()) != null)
{
line = line.Replace("oldvalue", "newvalue");
Console.WriteLine(line);
}
// close reader etc...
PS make sure your computer has more then 5mb of memory when you run this :D
One relatively easy option, which may not be the best solution depending on how many threads could be concurrently reading from different files, is to read the entire file into a string in memory and then use Regex to find the location of all {one} sections.
Using the Regex::Match::Index and Regex::Match::Length properties, you can find the start and and end your matching sections. Looping through all your matches, use these two properties to generate your new text string, which can either be written to a new file as your looping or at the very end.
If you would rather not load the entire file into a string, you'll have to have a stream that reads and a stream that writes to a new file. Read the file sections at a time while looking for your {one} (start) tag. Then replace everything after it with your new string until you find the closing {/one} tag. Once all is said and done, delete the old file, then rename the new file to the old file's filename.
Anyway, just a couple solutions. I'd have to see what all your project entails in order to better answer your question.
精彩评论