5

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?

hs2d
  • 6,027
  • 24
  • 64
  • 103
  • Looks fine although you should probably set the Position of the return stream to zero within the method for API neatness. Good solution for small files. – Tim Lloyd Aug 04 '11 at 12:47

3 Answers3

2

How about:

string final = string.Join("", File.ReadLines(path));

? This reads line-by-line, then re-combines without any separator.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2

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);
Tim Lloyd
  • 37,954
  • 10
  • 100
  • 130
  • 1
    This might not be an issue but if given the string `"\r\r\r"` the result would still be `"\r\r"`. You'd have to do the replace over and over until you get the same string back as you made the replace on. – aL3891 Aug 04 '11 at 10:51
  • @aL3891 Agreed, but from the sample text this would not occur. – Tim Lloyd Aug 04 '11 at 11:00
0

Replace Line Breaks in a String C#

The above has the answer. You could read in the file into a string and then remove the line breaks.

Community
  • 1
  • 1
ek_ny
  • 10,153
  • 6
  • 47
  • 60
  • I think he wants to remove them directly from the stream, but Yeah it would be better to just remove them once read into a stream. – Jethro Aug 04 '11 at 10:04
  • Yes, reading file into a string is my last option. Just wanted to know if there a way to do it right in the stream. – hs2d Aug 04 '11 at 10:05