.net 压缩多个文件到一个压缩,我想用户给文件路径使用逗号分隔

ghg1uchk  于 2022-12-27  发布在  .NET
关注(0)|答案(1)|浏览(113)
    • 我正在尝试这个**和它的工作正常。我想用户输入文件路径使用逗号分隔。我不明白如何采取单一的单一路径和添加到单一的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);
            }


        }

    }
}
    • 问题**:给定文件路径与逗号分隔,我想拆分路径,并添加到一个压缩文件中的每个文件添加。
6ojccjat

6ojccjat1#

要用逗号分隔文件路径并将每个文件添加到zip文件,可以使用以下方法:
首先,提示用户输入文件路径并将其存储在字符串变量中:

Console.WriteLine("Enter the file paths, separated by commas: ");
string filePaths = Console.ReadLine();

使用Split方法将文件路径字符串拆分为字符串数组:

string[] paths = filePaths.Split(',');

循环遍历文件路径数组,并将每个文件添加到zip文件中:

using (ZipArchive archive = ZipFile.Open(zipPath, ZipArchiveMode.Create))
{
    int i = 1;
    foreach (string path in paths)
    {
        archive.CreateEntryFromFile(path.Trim(), "file" + i + ".txt");
        i++;
    }
}

这将用逗号分隔文件路径,从每个路径中删除任何前导或尾随空格,并使用连续的文件名(例如“file1.txt”、“file2.txt”等)将每个文件添加到zip文件中。

相关问题