You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中解析逗号分隔文件路径并批量压缩至单个Zip文件

逗号分隔文件路径批量压缩到Zip的实现方案

当前实现现状

你当前的代码能正常实现固定4个文件的压缩,但需要改为支持用户输入逗号分隔的多文件路径,拆分后批量添加到单个Zip文件中。

你的现有代码如下:

using System;
using System.IO;
using System.IO.Compression;

namespace ConvertMultipleFilesIntoZip
{
    internal class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("..........Convert multiple files into a zip file...........");
                Console.WriteLine();
                Console.WriteLine();
                string zipPath = @"d:\\result" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".zip";

                using (ZipArchive archive = ZipFile.Open(zipPath, ZipArchiveMode.Create))
                {
                    Console.WriteLine("Enter the 1st file path, Which you want to add: ");
                    string sourcePath1 = Console.ReadLine();
                    Console.WriteLine("Enter the 2st file path, Which you want to add: ");
                    string sourcePath2 = Console.ReadLine();
                    Console.WriteLine("Enter the 3st file path, Which you want to add: ");
                    string sourcePath3 = Console.ReadLine();
                    Console.WriteLine("Enter the 4st file path, Which you want to add: ");
                    string sourcePath4 = Console.ReadLine();
                    archive.CreateEntryFromFile(sourcePath1, "file1.txt");
                    archive.CreateEntryFromFile(sourcePath2, "file2.txt");
                    archive.CreateEntryFromFile(sourcePath3, "file1.txt");
                    archive.CreateEntryFromFile(sourcePath4, "sanju1.nupkg");

                    /*archive.CreateEntryFromFile(@"d:\\file1.txt", "file1.txt");
                    archive.CreateEntryFromFile(@"c:\\Intel\\file2.txt", "file2.txt");
                    archive.CreateEntryFromFile(@"d:\\file1.txt", "file1.txt");
                    archive.CreateEntryFromFile(@"d:\\sanju1.nupkg", "sanju1.nupkg");*/

                }
                Console.WriteLine("Zip file path is " + zipPath + " .");
            }
            catch (FileNotFoundException dirEx)
            {
                Console.WriteLine("File does not exist: " + dirEx.Message);
            }
        }
    }
} 

修改后的实现方案

只需要调整输入逻辑,拆分逗号分隔的路径并循环处理即可,同时优化Zip内的文件名使用原文件名称,避免硬编码:

关键修改点

  • 提示用户输入逗号分隔的文件路径
  • 使用Split方法拆分路径,过滤空项(避免用户输入多余逗号)
  • 循环遍历每个路径,用Path.GetFileName()获取原文件名作为Zip条目名称
  • 增强异常处理,覆盖单个文件不存在的情况

修改后完整代码

using System;
using System.IO;
using System.IO.Compression;
using System.Linq;

namespace ConvertMultipleFilesIntoZip
{
    internal class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("..........Convert multiple files into a zip file...........");
                Console.WriteLine();
                Console.WriteLine("Enter file paths separated by commas: ");
                string inputPaths = Console.ReadLine()?.Trim() ?? string.Empty;

                if (string.IsNullOrEmpty(inputPaths))
                {
                    Console.WriteLine("No file paths provided.");
                    return;
                }

                // 拆分路径,移除空项,同时去除每个路径前后的空格
                string[] sourcePaths = inputPaths.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                 .Select(path => path.Trim())
                                                 .ToArray();

                string zipPath = @"d:\result" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".zip";

                using (ZipArchive archive = ZipFile.Open(zipPath, ZipArchiveMode.Create))
                {
                    foreach (string sourcePath in sourcePaths)
                    {
                        try
                        {
                            if (!File.Exists(sourcePath))
                            {
                                Console.WriteLine($"Warning: File not found - {sourcePath}, skipped.");
                                continue;
                            }
                            // 获取原文件名作为Zip内的条目名称
                            string entryName = Path.GetFileName(sourcePath);
                            archive.CreateEntryFromFile(sourcePath, entryName);
                            Console.WriteLine($"Added file: {sourcePath}");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"Failed to add {sourcePath}: {ex.Message}");
                        }
                    }
                }

                Console.WriteLine($"Zip file created successfully at: {zipPath}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error creating zip file: {ex.Message}");
            }
        }
    }
}

说明

  1. 路径拆分:使用Split按逗号拆分,通过StringSplitOptions.RemoveEmptyEntries过滤空路径,再用Trim()去除路径前后的空格(处理用户输入"d:\file1.txt, c:\file2.txt"这种带空格的情况)
  2. 文件名处理:用Path.GetFileName()自动获取原文件的名称,避免硬编码,保证Zip内的文件名和原文件一致
  3. 异常优化:在循环内单独捕获每个文件的异常,不会因为单个文件出错导致整个压缩任务失败,同时给出明确的提示信息
  4. 空输入处理:判断用户是否未输入任何路径,提前终止并提示

内容的提问来源于stack exchange,提问作者Sanjeev singh kushvaha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 13:15:51