当 C# 迭代 zipfile 时,HttpPostedFileBase 获取内容长度为 0

我有一个网络界面,用户可以从本地计算机中选择多个文件之一并将它们上传到中央位置,在本例中为Azure Blob Storage。我检查了我的C#代码以验证文件名结尾是否为.bin. 中的接收方法C#采用一个数组HttpPostedFileBase

我想允许用户选择一个 zip 文件。在我的C#代码中,我迭代 zip 文件的内容并检查每个文件名以验证结尾是否为.bin.

但是,当我迭代 zip 文件时,对象ContentLengthHttpPostedFileBase变为0(零),当我稍后将 zip 文件上传到 时Azure,它是空的。

如何在不操作 zip 文件的情况下检查文件名结尾?

  • 我尝试过DeepCopy单个对象,HttpPostedFileBase但它不可序列化。

  • 我试图复制该文件,array但没有任何作用。看来一切都是参考,没有价值。我的代码的一些示例如下。是的,我单独尝试了这些线路。


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

}

这就是我迭代 zip 文件的方式


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

                }

            }

        }

    }

}


慕村225694
浏览 194回答 1
1回答

30秒到达战场

我解决了我的问题。我必须做两件不同的事情:首先,我不做数组的副本。相反,对于每个 zip 文件,我只是复制流。这使得 ContentLength 保持在原来的长度。所做的第二件事是在查看 zip 文件后重置位置。我需要执行此操作,否则上传到 Azure Blob 存储的 zip 文件将为空。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;}
打开App,查看更多内容
随时随地看视频慕课网APP