Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# remove extra carriage returns from Stream

Tags:

c#

stream

Im reading file in as a stream: Stream fin = File.OpenRead(FilePath); Is there any way how i would be able to find and remove all carriage returns from that file stream?

EDIT: The goal is to remove single carriage-returns \r and leave the carriage returns what are with newline "\r\n" intact.

Example file:

The key backed up in this file is:\r
\r\n
pub   2048R/65079BB4 2011-08-01\r
\r\n
      Key fingerprint = 2342334234\r
\r\n
uid                  test\r
\r\n
sub   2048R/0B917D1C 2011-08-01\r

And the result should look like:

The key backed up in this file is:
\r\n
pub   2048R/65079BB4 2011-08-01
\r\n
      Key fingerprint = 2342334234
\r\n
uid                  test
\r\n
sub   2048R/0B917D1C 2011-08-01

EDIT2: The final solution what is working looks like this:

    static private Stream RemoveExtraCarriageReturns(Stream streamIn)
    {
        StreamReader reader = new StreamReader(streamIn);
        string key = reader.ReadToEnd();
        string final = key.Replace("\r\r", "\r");
        byte[] array = Encoding.ASCII.GetBytes(final);
        MemoryStream stream = new MemoryStream(array);
        return stream;
    }

I take in the Stream use StreamReader to read it into a string, then remove the extra carriage-return and write it back to a Stream. Does my code look ok or should i do something differently?

like image 779
hs2d Avatar asked Oct 11 '22 08:10

hs2d


1 Answers

After looking at your sample text, the following will remove your single 'r' instances:

string text = File.ReadAllText(FilePath);

text = text.Replace("\r\r", "\r");

File.WriteAllText(FilePath + ".modified", text);
like image 195
Tim Lloyd Avatar answered Oct 12 '22 23:10

Tim Lloyd