1

我有一个包含“1234567”的文件(test.txt)。但是,当我尝试使用 FileStream.Read 在 C# 上读取它时,我只得到 0(在这种情况下是七个零)。谁能告诉我为什么?我真的迷路了。

编辑:问题已解决,比较运算符错误。但是现在它返回“49505152535455”

编辑2:完成。作为记录,我必须将byte变量输出为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();
    }
}
4

3 回答 3

2

这条线

while (toRead < 0)

确保您从未真正阅读过。toRead 在循环之前将 >= 0。

之后,您转储从未填充的字节数组。

于 2009-10-22T17:48:50.663 回答
2
 foreach (byte b in bytes)
            {
                Console.Write(b.ToString());
            }

此代码不正确。它正在打印字节值的字符串值。即 ascii char '0' 为 49,'1' 为 50,等等。

您需要将其输出为

Console.Write(new Char(b).toString());
于 2009-10-22T17:56:48.187 回答
1

while (toRead < 0) 应该是 while (toRead > 0) (大于)

于 2009-10-22T17:47:57.643 回答