C# remove extra carriage returns from 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/0B917D开发者_如何学C1C 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?
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);
How about:
string final = string.Join("", File.ReadLines(path));
? This reads line-by-line, then re-combines without any separator.
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.
精彩评论