user222427
user222427

Reputation:

C# replacing items in textfile

I have a "|" delimited file that all I want to do is read all the lines in it and where "<\HRM>" exists replace it with "" (nothing). And where "HRM\" exists replace it with ;. It's got to write out everything in the same order it was read in.

I'd like to do this by just editing the original write, not writing a new one. If I have to write out a new file then i guess I have to.

Upvotes: 1

Views: 694

Answers (3)

David Basarab
David Basarab

Reputation: 73311

The question is how big is the file might change the solution or the very least slow it down.

using (StreamReader stream = new StreamReader(File.Open(@"YourFilePath", FileMode.Open)))
{
    string fileText = stream.ReadToEnd();

    // Do your replacements
    fileText = fileText.Replace(@"<\HRM>", string.Empty);
    fileText = fileText.Replace(@"HRM\", ";");

    using (StreamWriter writer = new StreamWriter(File.Open("@YourFilePath", FileMode.Create)))
    {
        // You do a create because the new file will have less characters than the old one
        writer.Write(fileText);
    }
}

Upvotes: 2

DRapp
DRapp

Reputation: 48139

you would have to re-write the file since you will be stripping characters out and thus making it more compact -- unless you wanted to replace your <\HRM> with equivalent spaces to retain position holdings.

String.Replace( "change this", "to this" )

Upvotes: 0

Jason Smith
Jason Smith

Reputation: 206

You want to write out a new one. There are good reasons for doing this, not the least of which is that it will be much much faster. It will also provide you with a degree of safety with your data (power loss will not result in potential data loss/corruption.

The generally accepted procedure is along the lines of of

  • Open new file
  • Write out new file
  • Move over top of old file

Upvotes: 0

Related Questions