我正在写一份关于求职面试的课程.一切都正常,除了一件事.当我使用外部方法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);
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我在外部方法中进行TotalLines计算时,问号不会显示.有什么想法吗?
文件很可能以字节顺序标记(BOM)开头,最初被读取器忽略,但是当你"回放"流时则不然.
虽然你可以创建一个新的阅读器,或者甚至只是在阅读它之后更换它,我认为最好避免两次读取文件开始:
foreach (var question in File.ReadLines(text, Encoding.Unicode))
{
Console.WriteLine(question);
string response = Console.ReadLine();
potentialEmployee.Responses.Add(question, response);
}
Run Code Online (Sandbox Code Playgroud)
这是更短,更简单,更高效的代码,也不会显示您询问的问题.
如果您想在询问任何问题之前确保可以阅读整个文件,那也很容易:
string[] questions = File.ReadAllLines(text, Encoding.Unicode);
foreach (var question in questions)
{
Console.WriteLine(question);
string response = Console.ReadLine();
potentialEmployee.Responses.Add(question, response);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
172 次 |
| 最近记录: |