C# SharpZipLib strips irrelevant directory names

放肆的年华 提交于 2019-12-23 17:30:57

问题


I am using SharpZipLib to zip up a folder with subdirectories and this is working fine. What I would like to do is strip off the parents directories of the first child file so the whole structure that is irrelevant isn't carried forth...

Example:

c:\a\b\c\d\e\f\g\h\file1.txt

c:\a\b\c\d\e\f\g\h\file2.txt

c:\a\b\c\d\e\f\g\h\i\file1.txt

c:\a\b\c\d\e\f\g\h\i\file2.txt

It should end up like this:

file1.txt

file2.txt

i\file1.txt

i\file2.txt

How can I do this?

Here is the code I have so far:

        ZipFile zipFile = new ZipFile(destinationArchive);

        zipFile.BeginUpdate();
        foreach (FileInfo file in sourceFiles)
        {
            zipFile.Add(file.FullName);
        }
        zipFile.CommitUpdate();

        zipFile.Close();

回答1:


Use ZipOutputStream instead:

string[] sourceFiles = new [] { @"c:\a\b\c\d\e\f\g\h\file1.txt", @"c:\a\b\c\d\e\f\g\h\i\file1.txt" };
FileStream fileStream = File.Create(@"c:\temp\test.zip");
ZipOutputStream zipOut = new ZipOutputStream(fileStream);
string baseDir = @"c:\a\b\c\d\e\f\g\h\";
foreach (var sourceFile in sourceFiles)
{
    ZipEntry entry = new ZipEntry(sourceFile.Replace(baseDir,""));
    zipOut.PutNextEntry(entry);

    FileStream inFile =  File.OpenRead(sourceFile);
    byte[] buffer = new byte[8192];
    int bytesRead = 0;
    while ((bytesRead = inFile.Read(buffer, 0, buffer.Length)) > 0)
    {
        zipOut.Write(buffer,0,bytesRead);
    }
    zipOut.CloseEntry();                
}
zipOut.Close();



回答2:


Or look on CodePlex for DotNetZip.



来源:https://stackoverflow.com/questions/1350653/c-sharp-sharpziplib-strips-irrelevant-directory-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!