Stream.Read总是返回0

时间:2015-09-01 08:21:16

标签: asp.net filestream memorystream asyncfileupload

我们正在使用asp.net的Asyncfileupload控件来上传文件,同样不起作用我们已调试并找到了这段代码:

input.Read(buffer, 0, buffer.Length)

返回0。

整个代码是这样的:

public static byte[] ReadFully(Stream input)
    {
        byte[] buffer = new byte[input.Length];
        using (MemoryStream ms = new MemoryStream())
        {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            return ms.ToArray();
        }
    }

1 个答案:

答案 0 :(得分:2)

如果您在字节数组的末尾或者网络连接中断,Stream.Read可能会返回0。您可以尝试以下代码来确保:

byte[] buffer = new byte[input.Length];
input.Position=0;
        using (MemoryStream ms = new MemoryStream())
        {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            return ms.ToArray();
        }