0

我有 c# 代码读取文本文件并将其打印出来,如下所示:

StreamReader sr = new StreamReader(File.OpenRead(ofd.FileName));
byte[] buffer = new byte[100]; //is there a way to simply specify the length of this to be the number of bytes in the file?
sr.BaseStream.Read(buffer, 0, buffer.Length);

foreach (byte b in buffer)
{
      label1.Text += b.ToString("x") + " ";
}

无论如何我可以知道我的文件有多少字节?

我想知道byte[] buffer提前的长度,以便在 Read 函数中,我可以简单地buffer.length作为第三个参数传入。

4

4 回答 4

8
System.IO.FileInfo fi = new System.IO.FileInfo("myfile.exe");
long size = fi.Length;

为了找到文件大小,系统必须从磁盘中读取。因此,上面的示例执行从磁盘读取数据但不读取文件内容。

于 2013-04-24T12:11:19.573 回答
7

StreamReader如果要读取二进制数据,目前还不清楚为什么要使用。改用就好FileStream了。您可以使用该Length属性来查找文件的长度。

但是请注意,这并不意味着您应该只调用Read并*假设一次调用将读取所有数据。你应该循环直到你读完所有内容:

byte[] data;
using (var stream = File.OpenRead(...))
{
    data = new byte[(int) stream.Length];
    int offset = 0;
    while (offset < data.Length)
    {
        int chunk = stream.Read(data, offset, data.Length - offset);
        if (chunk == 0)
        {
            // Or handle this some other way
            throw new IOException("File has shrunk while reading");
        }
        offset += chunk;
    }
}

请注意,这是假设您确实读取数据。如果您甚至不想打开流,请使用FileInfo.Length其他答案所示。请注意,两者FileStream.LengthFileInfo.Length的类型均为long,而数组的长度限制为 32 位。对于大于 2 gigs 的文件,您希望发生什么?

于 2013-04-24T12:11:31.433 回答
0

您可以使用FileInfo.Length方法。看一下链接中给出的示例。

于 2013-04-24T12:11:37.090 回答
0

我想这里的东西应该会有所帮助。

我怀疑您可以在不阅读文件的情况下先发制人地猜测文件的大小...

如何在块中使用 File.ReadAllBytes

如果是大文件;那么分块阅读可能会有所帮助

于 2013-04-24T12:12:54.697 回答