开发者

Why does this FileStream only return zeroes?

开发者 https://www.devze.com 2022-12-09 09:09 出处:网络
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

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.W开发者_开发百科riteLine("Oops! {0}", exc.Message);
        }
        finally
        {
            fil.Close();
        }


        Console.ReadLine();
    }
}


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消