如何找到no.不读取文本文件的字节数

本文关键字:取文本 文件 字节数 读取 何找 no | 更新日期: 2023-09-27 18:10:52

我有一个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作为第三个参数传入。

如何找到no.不读取文本文件的字节数

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

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

如果要读取二进制数据,则不清楚为什么要使用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位。对于大于2gb的文件,您希望发生什么?

您可以使用FileInfo。长度的方法。看一下链接中给出的例子。

我想这里应该有些帮助。

我怀疑你可以在不读取文件的情况下抢先猜出文件的大小…

我如何使用文件。ReadAllBytes In chunks

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