C# Zip return invalid file

29 views Asked by At

I have the following code to convert filenames from a Form Post into a zip and return them. When I run it i get the .zip file but it is invalid. Anyone see my error?

public IActionResult OnPost()
{
    Username = HttpContext.Session.GetString("Username");
    string[] FilePaths = Request.Form["FilePath"];
    Dictionary<string, byte[]> fileList = new Dictionary<string, byte[]>();
    byte[] retVal = null;

    foreach (var path in FilePaths)
    {
        string fullPath = Path.Combine(@"C:\Downloads\", Username, path);
        byte[] bytes = System.IO.File.ReadAllBytes(fullPath);
        fileList.Add(path, bytes);
    }

    using (MemoryStream zipStream = new MemoryStream())
    {
        using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
        {
            foreach (var file in fileList)
            {
                var demoFile = archive.CreateEntry(file.Key);

                using (var entryStream = demoFile.Open())
                using (var b = new BinaryWriter(entryStream))
                {
                    b.Write(file.Value);
                    b.Close();
                }
            }

            zipStream.Position = 0;

        }
        retVal = zipStream.ToArray();
    }
    return File(retVal, MediaTypeNames.Application.Zip, "test.zip");
}
1

There are 1 answers

2
Taranjeet Singh On

This code works for me, with the added condition to check if the file exists else it throws an exception. I have updated the code.

public IActionResult OnPost()
{
    Username = HttpContext.Session.GetString("Username");
    string[] FilePaths = Request.Form["FilePath"];
    Dictionary<string, byte[]> fileList = new Dictionary<string, byte[]>();
    byte[] retVal = null;

    foreach (var path in FilePaths)
    {
        string fullPath = Path.Combine(@"C:\Downloads\", Username, path);
        if (System.IO.File.Exists(fullPath))
        {
            byte[] bytes = System.IO.File.ReadAllBytes(fullPath);
            fileList.Add(path, bytes);
        }
    }

    using (MemoryStream zipStream = new MemoryStream())
    {
        using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
        {
            foreach (var file in fileList)
            {
                var demoFile = archive.CreateEntry(file.Key);

                using (var entryStream = demoFile.Open())
                using (var b = new BinaryWriter(entryStream))
                {
                    b.Write(file.Value);
                }
            }
        }
        zipStream.Position = 0;
        retVal = zipStream.ToArray();
    }

    return File(retVal, MediaTypeNames.Application.Zip, "test.zip");
}