Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a string within a stream in C# (without overwriting the original file)

I have a file that I'm opening into a stream and passing to another method. However, I'd like to replace a string in the file before passing the stream to the other method. So:

string path = "C:/...";
Stream s = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
//need to replace all occurrences of "John" in the file to "Jack" here.
CallMethod(s);

The original file should not be modified, only the stream. What would be the easiest way to do this?

Thanks...

like image 319
Prabhu Avatar asked Sep 16 '13 19:09

Prabhu


People also ask

How do I replace content in a string?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced.

How can I replace part of a string in C #?

In C#, Replace() method is a string method. This method is used to replace all the specified Unicode characters or specified string from the current string object and returns a new modified string. This method can be overloaded by passing arguments to it.

Does string replace replacing all occurrences?

The String type provides you with the replace() and replaceAll() methods that allow you to replace all occurrences of a substring in a string and return the new version of the string.


1 Answers

It's a lot easier if you just read in the file as lines, and then deal with those, instead of forcing yourself to stick with a Stream, simply because stream deals with both text and binary files, and needs to be able to read in one character at a time (which makes such replacement very hard). If you read in a whole line at a time (so long as you don't have multi-line replacement) it's quite easy.

var lines = File.ReadLines(path)
    .Select(line => line.Replace("John", "Jack"));

Note that ReadLines still does stream the data, and Select doesn't need to materialize the whole thing, so you're still not reading the whole file into memory at one time when doing this.

If you don't actually need to stream the data you can easily just load it all as one big string, do the replace, and then create a stream based on that one string:

string data = File.ReadAllText(path)
    .Replace("John", "Jack");
byte[] bytes = Encoding.ASCII.GetBytes(data);
Stream s = new MemoryStream(bytes);
like image 109
Servy Avatar answered Oct 04 '22 01:10

Servy