0

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.

inside
  • 3,047
  • 10
  • 49
  • 75

1 Answers1

3

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#

Community
  • 1
  • 1
tnw
  • 13,521
  • 15
  • 70
  • 111
  • I have many lines with different commands, and first I need to find specific line where I need to replace the SecurityGroup and only then write it back – inside Apr 19 '13 at 18:03
  • @Stanislav Like I said, you cannot simply replace one line in the file like that. You have to re-write the whole file. – tnw Apr 19 '13 at 18:05
  • hm, how can I read and write to the file at the same time so my line count would stay correct – inside Apr 19 '13 at 18:07
  • **YOU CAN'T DO THAT**. I don't know how much clearer I can make it. Your line count would not be affected with BOTH methods I've shown here. – tnw Apr 19 '13 at 18:09
  • @Stanislav I see your edit, are these examples not what you are looking for? – tnw Apr 19 '13 at 18:59