views:

68

answers:

3

I've got a file (test.txt) which contains "1234567". However when I try to read it on C# using FileStream.Read, I get only 0s (seven zeroes in this case). Could anyone tell me why? I'm really lost here.

Edit: Problem solved, wrong comparision operator. However now it's returning "49505152535455"

Edit 2: Done. For the record, I had to output the byte variable as a char.

using System;
using System.IO;

class Program
{
    static void Main()
    {

        FileStream fil = null;

        try
        {
            fil = new FileStream("test.txt", FileMode.Open,FileAccess.Read);

            byte[] bytes = new byte[fil.Length];
            int toRead = (int)fil.Length;
            int Read = 0;

            while (toRead < 0)
            {
                int n = fil.Read(bytes, Read, toRead);

                Read += n;
                toRead -= n;
            }

            //Tried this, will only return 0000000
            foreach (byte b in bytes)
            {
                Console.Write(b.ToString());
            }


        }
        catch (Exception exc)
        {
            Console.WriteLine("Oops! {0}", exc.Message);
        }
        finally
        {
            fil.Close();
        }


        Console.ReadLine();
    }
}
+1  A: 

while (toRead < 0) should be while (toRead > 0) (greater than)

Ray
+2  A: 

This line

while (toRead < 0)

makes sure you never actually read. toRead will be >= 0 before the loop.

Afterwards you dump the byte array that was never filled.

Henk Holterman
Thank you. However, now it's returning "49505152535455".
Daniel S
Clearly it has something to do with the character encoding or something: 49 50 51 52 53 54 55
Daniel S
Yes, you are seeing ASCII codes. Byte != char.
Henk Holterman
+2  A: 
 foreach (byte b in bytes)
            {
                Console.Write(b.ToString());
            }

This code is incorrect. It is printing the string value of the byte's value. ie 49 for the ascii char '0', 50 for '1', etc.

You need to output it as

Console.Write(new Char(b).toString());
Mike Clark
Or better still: Console.WriteLine(System.Text.Encoding.ASCII.GetString(bytes));
Jon Benedicto
Why would that be 'incorrect'? That totally depends on the intention.
Henk Holterman
It was incorrect, and Mike got the idea right. However that didn't compile, I had to cast b as a char instead.
Daniel S
Sorry about that, been a while since I have worked in C# and was trying to remember the exact conversion.
Mike Clark