I'm new to C#, working through some examples in the C# Head First book and trying to apply what I've learned in a practical manner. I'm trying to read in a text file with the following code:
private StreamReader upload;
private void Form1_Load(object sender, EventArgs e)
{
if (File.Exists(@"C:\Users\Recon 5\Desktop\ToDo.txt"))
{
upload = new StreamReader(@"C:\Users\Recon 5\Desktop\ToDo.txt");
while (upload.Peek() != null)
{
currentTasks.Items.Add(upload.ReadLine());
}
upload.Close();
}
}
The above code provides the intended result, i.e. adding items into a list box from a text file. What I don't understand is why the following expression:
upload.Peek() != null
is giving me the following compiler warning:
The result of the expression is always
true
since a value of typeint
is never equal tonull
of typeint
.
I've tried looking in the Windows library for a response, but understanding the API is a task in its own right.
I guess what I'm looking for is helpful pointers to either guide my search or resources to assist me in discovering the answer myself. I'm sure there might be a better way to write this task but given where I'm at with my understanding of the language I feel it important to use and understand the tools I have learned thus far, in this case the while
loop.
while (upload.Peek() != null)
...looks suspicious since StreamReader.Peek()
can't return null
. I suspect the correct line would be;
while (upload.Peek() != -1)
Return Value
Type: System.Int32
An integer representing the next character to be read, or -1 if there are no characters to be read or if the stream does not support seeking.