什么是读取字符一个字符的文件在C#中最简单的方法是什么?
What is the easiest way to read a file character by character in C#?
目前,我通过调用System.io.file.ReadLine阅读逐行()。我看到有一个read()函数,但它不;吨返回字符...
Currently, I am reading line by line by calling System.io.file.ReadLine(). I see that there is a Read() function but it doesn;t return a character...
我也想知道如何检测使用这样的方法行的结束......有问题的输入文件是一个CSV文件....
I would also like to know how to detect the end of a line using such an approach...The input file in question is a CSV file....
打开的TextReader
(按 File.OpenText - 请注意,
文件
是一个静态类,所以你的不能的创建它的一个实例)和重复调用的 读
。返回 INT
,而不是字符
所以它可以的也的指示文件的末尾:
Open a TextReader
(e.g. by File.OpenText
- note that File
is a static class, so you can't create an instance of it) and repeatedly call Read
. That returns int
rather than char
so it can also indicate end of file:
int readResult = reader.Read();
if (readResult != -1)
{
char nextChar = (char) readResult;
// ...
}
或者循环:
int readResult;
while ((readResult = reader.Read()) != -1)
{
char nextChar = (char) readResult;
// ...
}
或了解更多质朴的善良:
Or for more funky goodness:
public static IEnumerable<char> ReadCharacters(string filename)
{
using (var reader = File.OpenText(filename))
{
int readResult;
while ((readResult = reader.Read()) != -1)
{
yield return (char) readResult;
}
}
}
...
foreach (char c in ReadCharacters("foo.txt"))
{
...
}
请注意,所有在默认情况下, File.OpenText
将使用UTF-8的编码。指定编码明确,如果这是不是你想要的。
Note that all by default, File.OpenText
will use an encoding of UTF-8. Specify an encoding explicitly if that isn't what you want.
编辑:为了找到一个行的末尾,你会检查字符是否是 \ñ
...你可能要处理 \ r
特别是过,如果这是一个Windows的文本文件。
To find the end of a line, you'd check whether the character is \n
... you'd potentially want to handle \r
specially too, if this is a Windows text file.
但是,如果你希望每个的行的,为什么不叫的ReadLine
?你总是可以遍历字符的行之后...
But if you want each line, why not just call ReadLine
? You can always iterate over the characters in the line afterwards...