You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在不安装额外NuGet包的情况下打开并解压Zip文件?

问题:无需额外NuGet包能否在C# Timer Trigger函数中提取Zip文件内容?

用户提供的C# Timer Trigger函数代码如下:

public static class PracticeFunction 
{ 
    [FunctionName("LearningAboutFunctions")] 
    public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log) 
    { 
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}"); 
        using (var client = new WebClient()) 
        { 
            client.DownloadFile("https://examplesite.co.uk/file.zip", "myfile.zip"); 
        } 
    }
}

请问是否无需安装任何额外NuGet包,即可打开该Zip文件并提取其内容?


回答

好问题!答案是:在**现代.NET版本(.NET Core 3.1+、.NET 5及以上)**中,你完全不需要安装额外的NuGet包就能处理Zip文件——因为System.IO.Compression.ZipArchive和配套的文件操作API已经是.NET SDK的核心组成部分了。

不过有几个关键点需要注意:

  • 首先要在代码顶部引入using System.IO.Compression;命名空间
  • 在Azure Functions环境中,直接写入当前目录的文件可能会被清理(因为是临时存储),建议使用函数的持久存储路径或者临时目录环境变量来保存文件和提取内容
  • 要添加异常处理,避免下载的Zip文件损坏、路径权限不足等问题导致函数崩溃

下面是修改后的代码示例,加入了Zip文件提取逻辑:

using System.IO.Compression; // 必须引入这个命名空间

public static class PracticeFunction 
{ 
    [FunctionName("LearningAboutFunctions")] 
    public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log) 
    { 
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}"); 

        // 建议使用临时目录或者绑定的存储路径,避免文件丢失
        string tempDir = Environment.GetEnvironmentVariable("TEMP") ?? Directory.GetCurrentDirectory();
        string zipFilePath = Path.Combine(tempDir, "myfile.zip");
        string extractDir = Path.Combine(tempDir, "extracted_files");

        try
        {
            using (var client = new WebClient()) 
            { 
                client.DownloadFile("https://examplesite.co.uk/file.zip", zipFilePath); 
                log.LogInformation("Zip file downloaded successfully");
            }

            // 创建提取目录(如果不存在)
            Directory.CreateDirectory(extractDir);

            // 提取Zip文件内容
            using (ZipArchive archive = ZipFile.OpenRead(zipFilePath))
            {
                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    // 避免路径遍历漏洞,确保提取路径在指定目录内
                    string entryDestinationPath = Path.Combine(extractDir, entry.FullName);
                    if (!entryDestinationPath.StartsWith(extractDir, StringComparison.OrdinalIgnoreCase))
                    {
                        log.LogWarning($"Skipping potentially malicious entry: {entry.FullName}");
                        continue;
                    }

                    if (entry.FullName.EndsWith("/"))
                    {
                        Directory.CreateDirectory(entryDestinationPath);
                    }
                    else
                    {
                        entry.ExtractToFile(entryDestinationPath, overwrite: true);
                        log.LogInformation($"Extracted {entry.FullName} to {entryDestinationPath}");
                    }
                }
                log.LogInformation("Zip file extraction completed");
            }
        }
        catch (Exception ex)
        {
            log.LogError(ex, "Error occurred while downloading or extracting Zip file");
        }
    }
}

补充说明:

  • 如果你的函数仍然使用.NET Framework(而非.NET Core/.NET 5+),则需要安装System.IO.Compression.ZipFile NuGet包,但现在Azure Functions已经默认推荐使用现代.NET版本了
  • 代码中加入了路径安全检查,防止恶意Zip文件的路径遍历攻击,这是生产环境中必须的防护措施

内容的提问来源于stack exchange,提问作者Jordan1993

火山引擎 最新活动