为什么流不支持搜索操作? [英] Why does the stream not support the seek operation?

查看:71
本文介绍了为什么流不支持搜索操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用tcp/ip套件.我正在编写一个程序,在发送方加密文件,并在接收方解密.我用网络流的长度初始化字节数组时遇到了此异常.这是我的代码:

I'm currently working with tcp/ip suite. I'm writing a program to encrypt files at sender's end and decrypt at receiver's side. I came across this exception while initializing my byte array with the length that of network stream. Here's my code:

if (client.Connected)
{
    NetworkStream binarystream = client.GetStream();
    byte[] receivebytes = new byte[binarystream.Length];
    binarystream.Read(receivebytes, 0, receivebytes.Length);
    Stream file = File.OpenWrite(saveFileDialog1.FileName);
    file.Write(receivebytes, 0, receivebytes.Length);
    file.Close();
    binarystream.Close();
}

控制层次结构确保在组成二进制流实例之前,已经使用了 client.GetStream()返回的流.我得到的异常是在包含以下内容的行上:

The hierarchy of control ensures that the stream returned by client.GetStream() will have already been used for before making up binarystream instance. The exception I'm getting is on the line containing:

byte[] receivebytes = new byte[binarystream.Length];

它表示流不支持搜索操作.是什么意思?

It says that the stream doesn't support the seek operation. What does that mean?

推荐答案

要确定流的长度,您需要能够读取到流的末尾(即,您 Seek 结尾).由于这是一个网络流,因此您不能仅执行此操作,因此会遇到错误.您只需要继续将字节读入缓冲区中,直到流结束为止,直到那时您才知道有效负载的长度.这是一个建议:

To determine the length of a stream, you need to be able to read to the end of it (i.e. you Seek to the end). Since this is a network stream, you can't just do this, hence the error you're experiencing. You will need to just keep reading bytes into a buffer until the stream ends, and only then will you know the length of your payload. Here's a suggestion:

if (client.Connected)
{
    NetworkStream binarystream = client.GetStream();
    Stream file = File.OpenWrite(saveFileDialog1.FileName);

    byte[] buffer = new byte[10000];
    int bytesRead;
    while (binarystream.DataAvailable)
    {
        bytesRead = binarystream.Read(buffer, 0, buffer.Length);
        file.Write(buffer, 0, bytesRead);
    }

    file.Close();
    binarystream.Close();
}

请注意,我还建议您为每个流实例化添加 using 语句,因为这保证了即使在读/写过程中抛出异常,流也将被正确关闭.然后,您可以删除对 Close 的显式调用.

Note that I would also recommend adding using statements for each of your stream instantiations, as this guarantees that the streams will be closed properly even if an exception is thrown while reading/writing. You could then remove the explicit calls to Close.

这篇关于为什么流不支持搜索操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆