Search code examples
asp.netfilestreammemorystreamasyncfileupload

Stream.Read always returning 0


We are using Asyncfileupload control of asp.net to upload the file, the same is not working we have debugged and found this code:

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

returning 0.

The entire code is like this:

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();
        }
    }

Solution

  • Stream.Read may return 0 if you are at end of the byte array or your network connection is broken. You can try this line of code to make sure:

    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();
            }