将StreamReader设置为开头时出现奇怪的问号

问题描述 投票:5回答:2

我正在写一份关于求职面试的课程。一切都正常,除了一件事。当我使用外部方法TotalLines(我有单独的StreamReader)时,它工作正常,但是当我在程序中计算一些totalLines时,我在第一个问题的开头就收到一个问号。所以它是这样的:

?你叫什么名字?

但是在我正在阅读的文本文件中,我只是 - 你叫什么名字?

我不知道为什么会这样。也许这是我的问题,我将StreamReader重新开始?我检查了我的编码,一切,但没有任何效果。谢谢你的帮助 :)

PotentialEmployee potentialEmployee = new PotentialEmployee();
using (StreamReader InterviewQuestions = new StreamReader(text, Encoding.Unicode))
{
    int totalLines = 0;
    while (InterviewQuestions.ReadLine() != null)
    {
        totalLines++;
    }
    InterviewQuestions.DiscardBufferedData();
    InterviewQuestions.BaseStream.Seek(0, SeekOrigin.Begin);

    for (int numberOfQuestions = 0; numberOfQuestions < totalLines; numberOfQuestions++)
    {
        string question = InterviewQuestions.ReadLine();
        Console.WriteLine(question);
        string response = Console.ReadLine();
        potentialEmployee.Responses.Add(question, response);
    }
}

但是当我在外部方法中进行TotalLines计算时,问号不会显示。有什么想法吗?

c# streamreader
2个回答
8
投票

文件很可能以byte order mark (BOM)开头,而foreach (var question in File.ReadLines(text, Encoding.Unicode)) { Console.WriteLine(question); string response = Console.ReadLine(); potentialEmployee.Responses.Add(question, response); } 最初被读者忽略,但当你“回放”流时则不然。

虽然你可以创建一个新的阅读器,或者甚至只是在阅读它之后更换它,我认为最好避免两次读取文件开始:

string[] questions = File.ReadAllLines(text, Encoding.Unicode);
foreach (var question in questions)
{
    Console.WriteLine(question);
    string response = Console.ReadLine();
    potentialEmployee.Responses.Add(question, response);
}

这是更短,更简单,更高效的代码,也不会显示您询问的问题。

如果您想在询问任何问题之前确保可以阅读整个文件,那也很容易:

qazxswpoi

2
投票

无论何时开始寻找流,都不会再次读取字节顺序标记(BOM),只有在创建指定了编码的流读取器后才会首次执行。

为了再次正确读取BOM,您需要创建一个新的流读取器。但是,如果您指示流阅读器在阅读器处理后保持流打开,则可以重用该流,但在创建新阅读器之前一定要查找。

© www.soinside.com 2019 - 2024. All rights reserved.