tags:

views:

53

answers:

5

I have the following code to read a file in the root directory of my application. For some reason, no matter how many runs, my file is still not being read. Any idea what I could be doing wrong here please. Thanks in advance.

byte[] mybytes = null;
if (File.Exists(filename))
{
    using (StreamReader sr = new StreamReader(new FileStream(filename, 
                               FileMode.Open, FileAccess.Read, FileShare.Read)))
    {
        String input;
        StringBuilder tempstore = new StringBuilder();
        while ((input  = sr.ReadLine()) != null)
        {
            tempstore.Append(input);
        }
        mybytes = Encoding.ASCII.GetBytes(tempstore.ToString());
        sr.Close();
    }
}
+1  A: 

Have you tried File.ReadAllText(filename); ?

It's easier.

John Buchanan
I tried that first before deciding on what I have above.
Kobojunkie
A: 

ReadLine should only be used with text files. If your file is binary it could have a ^Z character at the beginning.. making the library think that it reached the EOF.

Nestor
Good Point, as he is ultimately putting it into `byte[]` this might be the case
TheVillageIdiot
file name actually refers to string filename = @"outfile.txt";
Kobojunkie
It doesn't matter. It could be a binary file with extension .txt. Try opening it with Notepad
Nestor
A: 

Your code works for me if I copy it verbatim, add my own filename variable and run it. Is it possible that the value of filename is not a valid file path on your machine?

Andrew Hare
but he is checking `File.Exists(filename)`
TheVillageIdiot
It passes the if (File.Exists(filename)) { ...}check, indicating that the file does exist, it stops short at the line ... while ((input = sr.ReadLine()) != null) {Where it reads null and breaks out of my loop immediately.
Kobojunkie
+1  A: 

Have you tried File.ReadAllBytes?

        byte[] mybytes = File.ReadAllBytes(filename);
Simon
I initially had it as you have it there ( File.ReadAllBytes(filename)) and that did not work. So I switched it over to what I have now and still nothing.
Kobojunkie
Well...ReadAllBytes should work just fine...
Nestor
A: 

Are you sure the filename actually exists? That is really the most likely thing that could be the problem based on the code you've listed.

ecounysis