【问题标题】:Strange question mark, when setting StreamReader to beginning奇怪的问号,将 StreamReader 设置为开始时
【发布时间】:2019-02-13 12:15:14
【问题描述】:

我正在编写一个关于求职面试的程序。一切正常,除了一件事。当我使用外部方法 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 计算时,不会显示问号。有什么想法吗?

【问题讨论】:

  • 这是由于编码。使用记事本打开文件并在打开的弹出窗口中选择 unicode 而不是 ANSI(默认)。
  • @jdweng:我认为这更有可能是由于 BOM 而不是编码。
  • @jdweng 不是真的,我刚刚将编码更改为 Unicode、UTF-8、ANSI,问号还在。

标签: c# streamreader


【解决方案1】:

文件很可能以 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);
}

【讨论】:

    【解决方案2】:

    当您从头开始寻找流时,不会再次读取字节顺序标记 (BOM),只会在您创建指定编码的流读取器后第一次读取。

    为了再次正确读取 BOM,您需要创建一个新的流读取器。但是,如果您指示流阅读器在释放阅读器后保持流打开,则可以重用该流,但请务必在创建新阅读器之前进行搜索。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 2012-09-30
      • 1970-01-01
      相关资源
      最近更新 更多