I have a log file (.txt) which has information as below:
Filename1 - A3332NCDER
Filename2 - B3332NCDER
Filename3 - B1222NCDERE
Filename4 - C1222NCDER
Filename4 - C1222NCDERE
Each line holds the filename and the corresponding ID. Now I am picking the ID’s and assigning it to the List.
char[] delimiters = new char[]{'\n','\r','-'};
IList<string> fileIDs = File.ReadAllText(logFileName)
.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
.Where((lineItem, index) => index % 2 == 1)
.Select(lineItem => lineItem.Trim())
.ToList();
I am writing to the log file as below:
using (StreamWriter logFile = new StreamWriter(logFileName, true))
{
logFile.WriteLine(fileName + " - " + fileID);
}
This works fin开发者_运维知识库e.I am curious to know why WriteLine method adds both \n
and \r
.
Thanks
This is a historical baggage from the time when we used type writers. To end the current line and begin a new line, you would have to do two things:
- Move the carriage back to the start of the line -
"Carriage Return"
orCR
for short - Move the paper up so you get a blank line to write on -
"Line Feed"
orLF
for short
Of course, none of this is necessary on a computer, but old habits die hard...
Different operating systems use different line ending characters (or sequence of them) but for the big systems:
- Windows: CR + LF
- Unix/Linux/OS X: LF
- Old Macs (v9 and earlier): CR
For more information and a bigger list of OS specific line endings, see wikipedias article on Newline.
In .NET, there is a static property called Environment.Newline that contains the appropriate line ending string based on which system your application is running on.
Regarding your code, you could simplify it a bit and just call File.ReadAllLines() and you'll get an array containing all lines. That way you don't have to bother with String.Split etc.
Or if you are ok with a .NET 4 dependency, use File.ReadLines which will lazy read one line at a time so you don't have to store the entire file in memory. Or thirdly, you can do the old but faithful ReadLine method:
string line;
while ((line = myFile.ReadLine()) != null)
{ /* do stuff to line here */ }
The default line terminator is a string whose value is a carriage return followed by a line feed ("\r\n" in C#, or vbCrLf in Visual Basic).
http://msdn.microsoft.com/en-us/library/zdf6yhx5.aspx
The terminator can be changed by setting Console.Out.NewLine
, eg: Console.Out.NewLine = "\r\n\r\n";
That's why it's WriteLine. If you don't want the standard line terminator \n\r then use Write
It is a Microsoft standard line ending to have '\r\n'. It comes from the days of typewriters. Originally, the 1st character was to move down one line, and the 2nd character moved to the beginning of the current line. Thus, taken together, you get to the beginning of the next line.
精彩评论