如何将文件添加到.net核心中的zip文件夹中?

时间:2017-04-03 08:22:53

标签: .net core zipfile ziparchive

我需要从文件夹中读取文件并将其放在.Net核心中的zip文件夹中。 我搜索了这个并找到了Adding files into a folder inside a zip file in c#,但这对我不起作用。

我的zip文件代码是:

using (var fs = new FileStream("Test.zip", FileMode.Create))
using (var zip = new ZipArchive(fs, ZipArchiveMode.Create))
{
    zip.CreateEntry("Folder1 /"); 
}// working till here, Creates a zip and then creates Folder 1 inside Test.zip`

但是我需要从“C:\ Files”中读取一个文件并将其放在“Folder1”中。该文件被添加到zip文件中但不在“Folder1”中。

1 个答案:

答案 0 :(得分:1)

这段代码似乎可以解决问题:

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

class Program
{
    static void Main(string[] args)
    {
        string sourceFileName = "MyFile.txt";
        string sourceFolder = @"C:\Files";
        string zipFilePath = Path.Combine(@"C:\Files", "Test.zip");

        using (ZipArchive archive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create))
        {
            archive.CreateEntryFromFile(Path.Combine(sourceFolder, sourceFileName), $"Folder1\\{sourceFileName}");
        }
    }
}
相关问题