简体   繁体   中英

Find regex in file with StreamReader and overwrite it with StreamWriter

I am reading text file with StreamReader and doing Regex.Match to find specific info, now when I found it I want to replace it with Regex.Replace and I want to write this replacement back to the file.

this is text inside my file:

/// 
/// <Command Name="Press_Button"  Comment="Press button" Security="Security1">
/// 
/// <Command Name="Create_Button"  Comment="Create button" Security="Security3">
/// ... lots of other Commands 

now I need to find : Security="Security3"> in Create_Button command, change it to Security="Security2"> and write it back to the file

do { 
    // read line by line 
    string ReadLine = InfoStreamReader.ReadLine();

    if (ReadLine.Contains("<Command Name"))
     {
         // now I need to find Security1, replace it with Security2 and write back to the file
     }
   }
while (!InfoStreamReader.EndOfStream);

any ideas are welcome...

EDITED: Good call was from tnw to read and write to the file line by line. Need an example.

I'd do something more like this. You can't directly write to a line in the file like you're describing there.

This doesn't use regex but accomplishes the same thing.

var fileContents = System.IO.File.ReadAllText(@"<File Path>");

fileContents = fileContents.Replace("Security1", "Security2"); 

System.IO.File.WriteAllText(@"<File Path>", fileContents);

Pulled pretty much directly from here: c# replace string within file

Alternatively, you could loop thru and read your file line-by-line and write it line-by-line to a new file. For each line, you could check for Security1 , replace it, and then write it to the new file.

For example:

StringBuilder newFile = new StringBuilder();

string temp = "";

string[] file = File.ReadAllLines(@"<File Path>");

foreach (string line in file)
{
    if (line.Contains("Security1"))
    {

    temp = line.Replace("Security1", "Security2");

    newFile.Append(temp + "\r\n");

    continue;

    }

newFile.Append(line + "\r\n");

}

File.WriteAllText(@"<File Path>", newFile.ToString());

Source: how to edit a line from a text file using c#

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM