文件流仅读取文件的前 4 个字符

发布于 2024-11-04 20:04:18 字数 407 浏览 0 评论 0原文

嘿!我正在尝试使用文件流读取 150mb 文件,但每次执行此操作时,我得到的都是: |zl 而不是整个流。请注意,其中有一些特殊字符。

有人知道可能是什么问题吗?这是我的代码:

using (FileStream fs = File.OpenRead(path))
{
    byte[] buffer = new byte[fs.Length];
    fs.Read(buffer, 0, buffer.Length);
    extract = Encoding.Default.GetString(buffer);
}

编辑:
我尝试阅读所有文本,但它仍然返回相同的四个字符。除了这几个文件之外,它在任何其他文件上都可以正常工作。当我使用读取所有行时,它只获取第一行。

Hey there! I'm trying to read a 150mb file with a file stream but every time I do it all I get is: |zl instead of the whole stream. Note that it has some special characters in it.

Does anybody know what the problem could be? here is my code:

using (FileStream fs = File.OpenRead(path))
{
    byte[] buffer = new byte[fs.Length];
    fs.Read(buffer, 0, buffer.Length);
    extract = Encoding.Default.GetString(buffer);
}

Edit:
I tried to read all text but it still returned the same four characters. It works fine on any other file except for these few. When I use read all lines it only gets the first line.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

公布 2024-11-11 20:04:18

fs.Read() 不会一次读取全部字节,它会读取一定数量的字节并返回读取的字节数。 MSDN 有一个很好的示例,说明如何使用它来获取整个文件:

http: //msdn.microsoft.com/en-us/library/system.io.filestream.read.aspx

就其价值而言,将整个 150MB 数据读入内存确实会耗尽客户端的资源系统——首选就是对其进行优化,这样您就不需要一次需要整个文件。

fs.Read() does not read the whole smash of bytes all at once, it reads some number of bytes and returns the number of bytes read. MSDN has an excellent example of how to use it to get the whole file:

http://msdn.microsoft.com/en-us/library/system.io.filestream.read.aspx

For what it's worth, reading the entire 150MB of data into memory is really going to put a drain on your client's system -- the preferred option would be to optimize it so that you don't need the whole file all at once.

最美不过初阳 2024-11-11 20:04:18

如果您想以这种方式阅读文本 File.ReadAllLine (或 ReadAllText) - http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx" rel="nofollow">http:// /msdn.microsoft.com/en-us/library/s2tte0y1.aspx 是更好的选择。

我猜该文件不是文本文件,并且显示结果字符串的方式确实停在 0 个字符处。

正如 debracey 指出的那样,Read 返回读取的字节数 - 检查一下。同样对于文件操作来说,它不太可能停在 4 个字符处......

If you want to read text this way File.ReadAllLine (or ReadAllText) - http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx is better option.

My guess the file is not text file to start with and the way you display resulting string does stop at 0 characters.

As debracey pointed out Read returns number of bytes read - check that out. Also for file operations it is unlikely to stop at 4 characters...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文