Как скопировать файл из одного ZipArchive в другой - PullRequest
0 голосов
/ 03 апреля 2019

Я хочу иметь возможность скопировать файл из существующего zip-файла в новый zip-файл.

Насколько я вижу, есть два способа сделать это, но ни один из них не работает.

Я мог бы использовать

archive.CreateEntryFromFile(file.FullPath, file.Name + "." + file.Extention);

Однако имя файла«C: \ For Attachment \ atest3_1.zip \ BR_FEE_VerifyFeePackContent_S.sql», и это приводит к следующей ошибке:

Не удалось найти часть пути «C: \ For Attachment \ atest3_1.zip \ BR_FEE_VerifyFeePackContent_S.sql '.

Итак, возможно, мне нужно извлечь содержимое файла в zip-архиве, а затем записать его в новый архив, используя следующий код:

zipItem = archive.CreateEntry(file.Name + "." + file.Extention);                           
using (Stream sourceStream = file.MemoryStream)
{
    using (Stream destinationStream = zipItem.Open())
    {
        sourceStream.CopyTo(destinationStream);
    }
}

Thisсоздает файл без каких-либо ошибок, но затем файлы становятся пустыми - содержимое фактически не перемещается.

Весь метод выглядит следующим образом:

    private void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            string fileName = "";
            if (FormatFileName(out fileName))
            {
                SourceFile file;
                ZipArchiveEntry zipItem;
                using (ZipArchive archive = ZipFile.Open(fileName, ZipArchiveMode.Create))
                {
                    for (int i = 0; i < lstIncludedFiles.Items.Count; i++)
                    {
                        file = new SourceFile(lstIncludedFiles.Items[i].ToString());

                        zipItem = archive.CreateEntry(file.Name + "." + file.Extention);                           
                        using (Stream sourceStream = file.MemoryStream)
                        {
                            using (Stream destinationStream = zipItem.Open())
                            {
                                //destinationStream.Flush();
                                sourceStream.CopyTo(destinationStream);
                            }
                        }



                        //archive.CreateEntryFromFile(file.FullPath, file.Name + "." + file.Extention);
                    }
                }
                Clipboard.SetText(fileName);
                MessageBox.Show(this, fileName + " was created and the name copied to your clipboard.", "Operation Completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        catch (Exception ex)
        {
            ShowError(ex);
        }
    }
    private void ShowError(Exception ex)
    {
        MessageBox.Show(this, ex.Message, "An error has occured", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    }

И класс исходного файла:

public class SourceFile
{
    private string _name;
    private string _fullPath;
    private string _extention;
    private MemoryStream _memoryStream;
    private Byte[] _fileBytes;

    public SourceFile(string fullPath)
    {
        _fullPath = fullPath.Replace(" \\ ", "\\");
        _name = _fullPath.Split('\\')[_fullPath.Split('\\').Length - 1];
        _extention = _name.Split('.')[_name.Split('.').Length - 1];
        _name = _name.Replace("." + _extention, "");
        FileStream fs;
        _memoryStream = new MemoryStream();
        if (_fullPath.Contains(".zip\\"))
        {

            string zipFilePath = _fullPath.Substring(0, _fullPath.IndexOf(".zip\\") + 4);
            ZipArchive zipFile = ZipFile.OpenRead(zipFilePath);
            ZipArchiveEntry file = null;
            for (int i = 0; ((file == null) && (i < zipFile.Entries.Count)); i++)
            {
                if (zipFile.Entries[i].FullName == _fullPath.Split('\\')[_fullPath.Split('\\').Length - 1])
                {
                    file = zipFile.Entries[i];
                }
            }               
            file.Open().CopyTo(_memoryStream);               

        }
        else
        {
            fs = new FileStream(_fullPath, FileMode.Open, FileAccess.Read);
            fs.CopyTo(_memoryStream);
            /*
            br = new BinaryReader(fs);
            long numBytes = new FileInfo(_fullPath).Length;
            _fileBytes = br.ReadBytes((int)numBytes);
            _memoryStream = new MemoryStream(_fileBytes);
            */
        }            

    }
    public string FullPath
    {
        get { return _fullPath; }
    }
    public string Name
    {
        get { return _name; }
    }

    public string Extention
    {
        get { return _extention; }
    }

    public Byte[] FileBytes
    {
        get { return _fileBytes; }
    }

    public MemoryStream MemoryStream
    {
        get { return _memoryStream; }
    }
}
...