Strange question mark, when setting StreamReader to beginning

  • A+
Category:Languages

I am writing a program about job interview. Everything is working properly, except one thing. When I use an outside method TotalLines (where I have seperate StreamReader), it is working properly, but when I am calculating a number of totalLines in the program, I am receiving one question mark on the beginning of the first question. So it is like that:

?What is your name?

but in the text file from which I am reading, I have just - What is your name?

I have no idea why is that. Maybe it is problem with that I am returning StreamReader to beginning? I checked my encoding, everything, but nothing worked. Thanks for your help :)

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

But when I have a TotalLines calculation in the outside method, the question mark does not show. Any ideas plase?

 


It's very likely that the file starts with a byte order mark (BOM) which is being ignored by the reader initially, but then not when you "rewind" the stream.

While you could create a new reader, or even just replace it after reading it, I think it would be better to just avoid reading the file twice to start with:

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

That's shorter, simpler, more efficient code that also won't display the problem you asked about.

If you want to make sure you can read the whole file before asking any questions, that's easy too:

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: