Martin Nilsson
Martin Nilsson

Reputation: 519

HttpPostedFileBase gets content length to 0 when C# iterates the zipfile

I have a web interface where users can choose one of many files from local computer and upload them to a central location, in this case Azure Blob Storage. I have a check in my C# code to validate that the filename ending is .bin. The receiving method in C# takes an array of HttpPostedFileBase.

I want to allow users to choose a zipfile instead. In my C# code, I iterate through the content of the zipfile and check each filename to verify that the ending is .bin.

However, when I iterate through the zipfile, the ContentLength of the HttpPostedFileBase object becomes 0 (zero) and when I later on upload the zipfile to Azure, it is empty.

How can I make a check for filename endings without manipulating the zipfile?


private static bool CanUploadBatchOfFiles(HttpPostedFileBase[] files)
{
    var filesCopy = new HttpPostedFileBase[files.Length];
    // Neither of these lines works
    Array.Copy(files, 0, filesCopy, 0, files.Length);
    Array.Copy(files, filesCopy, files.Length);
    files.CopyTo(filesCopy, 0);
}

This is how I iterate through the zipfile

foreach (var file in filesCopy)
{
    if (file.FileName.EndsWith(".zip"))
    {
        using (ZipArchive zipFile = new ZipArchive(file.InputStream))
        {
            foreach (ZipArchiveEntry entry in zipFile.Entries)
            {
                if (entry.Name.EndsWith(".bin"))
                {
                    // Some code left out
                }
            }
        }
    }
}

Upvotes: 0

Views: 1695

Answers (1)

Martin Nilsson
Martin Nilsson

Reputation: 519

I solved my problem. I had to do two separate things:

First, I do not do a copy of the array. Instead, for each zip file, I just copy the stream. This made the ContentLength stay at whatever length it was.

The second thing is did was to reset the position after I looked inside the zipfile. I need to do this or else the zip file that I upload to Azure Blob Storage will be empty.

private static bool CanUploadBatchOfFiles(HttpPostedFileBase[] files)
{
    foreach (var file in files)
    {
        if (file.FileName.EndsWith(".zip"))
        {
            // Part one of the solution
            Stream fileCopy = new MemoryStream();
            file.InputStream.CopyTo(fileCopy);

            using (ZipArchive zipFile = new ZipArchive(fileCopy))
            {
                foreach (ZipArchiveEntry entry in zipFile.Entries)
                {
                    // Code left out
                }
            }

            // Part two of the solution
            file.InputStream.Position = 0;
        }
    }

    return true;
}

Upvotes: 1

Related Questions