C# 如何在不读取文本文件的情况下查找文本文件的字节数?

C# 如何在不读取文本文件的情况下查找文本文件的字节数?,c#,string,streamreader,C#,String,Streamreader,我使用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, buffe

我使用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[]缓冲区的长度,以便在Read函数中,我可以简单地传入buffer.length作为第三个参数

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

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

如果要读取二进制数据,则不清楚为什么要使用StreamReader。只需使用文件流即可。您可以使用该属性查找文件的长度

但是,请注意,这并不意味着您应该只调用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;
    }
}
注意,这是假设您确实想要读取数据。如果您甚至不想打开流,请使用其他答案。请注意,FileStream.Length和FileInfo.Length都具有long类型,而数组的长度限制为32位。对于大于2 Gig的文件,您希望发生什么情况?

您可以使用该方法。
请看链接中给出的示例。

我想这里有些东西会有所帮助

我怀疑你能在不阅读文件的情况下先发制人地猜出文件的大小


如果是大文件;然后分块读取可能会有帮助

如果它是一个小的文本文件,那么可能会有重复。读取数据的最简单方法就是System.IO.file.ReadAllTextfile name。我想您可能希望使用FileShare.None或.read打开流,以避免文件大小从您的读取脚下突然变大,对吗?当有这么多的方式读写文件的时候,真的很困惑——BinaryReader、BinaryWriter、StreamReader、StreamWriter,现在还有这个我从来都不知道的文件流。谢谢你的回答。@asawyer:可能吧。这取决于你是想检测还是阻止它。。。