简体   繁体   中英

IOException file already exists C#

private void btn_Backup_Click(object sender, EventArgs e)
    {
        List<DirectoryInfo> SourceDir = this.lbox_Sources.Items.Cast<DirectoryInfo>().ToList();
        string TargetDir = this.tbox_Target.Text;

        foreach (DirectoryInfo directory in SourceDir)
        {
            foreach (var file in directory.GetFiles())
                if (this.checkbox_zipfiles.Checked == true)
                {
                    System.IO.Compression.ZipFile.CreateFromDirectory(directory.FullName, TargetDir + @"\test.zip");
                }
                else
                {
                    Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(directory.FullName, TargetDir, true);
                }
        }
    }

I'm creating a backup application and when I try to zip the files I need to backup it says: "The file 'C:\\Users\\Lada1208\\Desktop\\test\\test.zip' already exists." even thought the folder is empty before so it's trying to create the test.zip file two times for some reason. Any idea why?

As pointed out by sm in the comment above, the call to ZipFile.CreateFromDirectory() will attempt to create a zip file with the same location and file name for all the source directories.

If the intention is to create a single archive containing files from all the source directories, then the Zipfile.CreateFromDirectory() "shortcut" method cannot be used. Instead, you need to call ZipFile.Open(), get a ZipArchive object and use its CreateEntry() method to add every file individually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM