WriteLine方法 [英] WriteLine Method

查看:36
本文介绍了WriteLine方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日志文件(.txt),其中包含以下信息:

I have a log file (.txt) which has information as below:

Filename1 -  A3332NCDER
Filename2 -  B3332NCDER
Filename3 -  B1222NCDERE
Filename4 -  C1222NCDER
Filename4 -  C1222NCDERE

每行包含文件名和相应的ID.现在,我选择ID并将其分配给列表.

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);
}

这很好用.我很好奇为什么WriteLine方法同时添加了 \ n \ r .

This works fine.I am curious to know why WriteLine method adds both \n and \r.

谢谢

推荐答案

这是我们使用类型编写器以来的历史包bag.要结束当前行并开始新行,您必须做两件事:

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:

  1. 将车架移回行的开头-回车" 或简称为 CR
  2. 向上移动纸张,以便在空白行上写-换行" 或简称为 LF
  1. Move the carriage back to the start of the line - "Carriage Return" or CR for short
  2. Move the paper up so you get a blank line to write on - "Line Feed" or LF 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
  • 旧Mac(v9和更低版本):CR

有关更多信息和特定于操作系统的行结尾的更多列表,请参见换行符上的Wikipedias文章.

For more information and a bigger list of OS specific line endings, see wikipedias article on Newline.

.NET中有一个名为环境的静态属性.换行符,其中包含基于您的应用程序所运行的系统的适当的行尾字符串.

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.

或者,如果您对.NET 4有依赖性,请使用 File.ReadLines一次将懒惰地读取一行,因此您不必将整个文件存储在内存中.或第三,您可以执行旧的但忠实的 ReadLine 方法:

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 */ } 

这篇关于WriteLine方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆