Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# BinaryReader Cannot access a closed file

Controller:

private readonly Dictionary<string, Stream> streams;

        public ActionResult Upload(string qqfile, string id)
        {
            string filename;
            try
            {
                Stream stream = this.Request.InputStream;
                if (this.Request.Files.Count > 0)
                {
                    // IE
                    HttpPostedFileBase postedFile = this.Request.Files[0];
                    stream = postedFile.InputStream;
                }
                else
                {
                    stream = this.Request.InputStream;
                }

                filename = this.packageRepository.AddStream(stream, qqfile);
            }
            catch (Exception ex)
            {
                return this.Json(new { success = false, message = ex.Message }, "text/html");
            }

            return this.Json(new { success = true, qqfile, filename }, "text/html");
        }

method for adding stream:

        public string AddStream(Stream stream, string filename)
        {

            if (string.IsNullOrEmpty(filename))
            {
                return null;
            }

            string fileExt = Path.GetExtension(filename).ToLower();
            string fileName = Guid.NewGuid().ToString();
            this.streams.Add(fileName, stream);
        }

I'm trying read a binary stream like so:

Stream stream;
            if (!this.streams.TryGetValue(key, out stream))
            {
                return false;
            }

    private const int BufferSize = 2097152;

                            using (var binaryReader = new BinaryReader(stream))
                            {
                                int offset = 0;
                                binaryReader.BaseStream.Position = 0;
                                byte[] fileBuffer = binaryReader.ReadBytes(BufferSize); // THIS IS THE LINE THAT FAILS
    ....

When I view stream in debug mode it shows that it can be read = true, seek = true, lenght = 903234 etc.

but I keep getting: Cannot access a closed file

This works fine when I run mvc site locally/debug mode (VS IIS) and DOES NOT WORK when in "RELEASE" mode (when site is published to iis).

what am I doing wrong?

like image 293
ShaneKm Avatar asked Feb 18 '23 13:02

ShaneKm


1 Answers

Found solution here:

uploading file exception

Solution:

add "requestLengthDiskThreshold" on production envirenment

<system.web>
<httpRuntime executionTimeout="90" maxRequestLength="20000" useFullyQualifiedRedirectUrl="false" requestLengthDiskThreshold="8192"/>
</system.web>
like image 182
ShaneKm Avatar answered Feb 28 '23 08:02

ShaneKm