c# - 即使文件正在使用中,如何在 C# 中压缩文件夹内容

标签 c# winforms zip backup

我正在学习 C#,想使用 C# winforms 创建一个简单的备份程序。

我有程序可以压缩文件夹并将其移动到另一个位置,当文件不使用时没有问题。如果文件正在使用中,或者至少忽略正在使用的文件并继续压缩其余文件,我该如何做同样的事情。

我理想的解决方案是复制并压缩所有文件,即使它们正在使用,如果失败,我想压缩所有可以压缩的文件并打印丢失的文件列表。

这是我用来压缩并发送到另一个位置的代码

 private void btnZip_Click(object sender, EventArgs e)
    {
        string fromDirectory = txtBackupFrom.Text;
        string todaysDate = DateTime.Now.ToString("dd_MMM_yyyy");
        string toDirectory = txtBackupToLocation.Text + "/" + todaysDate + "_backup.zip";

        try
        {
            ZipFile.CreateFromDirectory(fromDirectory, toDirectory, CompressionLevel.Optimal, true);
            //Write the current date to the text file

            StreamWriter writer = new StreamWriter(runningDirectory + "\\BackupDate.txt"); //open the file for writing.
            writer.Write(DateTime.Now.ToString("dd MMM yyyy")); //write the current date to the file. change this with your date or something.
            writer.Close(); //remember to close the file again.
            writer.Dispose(); //remember to dispose it from the memory.

            MessageBox.Show("Backup Successful");
        }
        catch (Exception zipException)
        {
            MessageBox.Show(zipException.Message);
        }
    }

/********编辑如下*************/

这是我尝试解决问题的方法。这可能不是我正在学习的最好方法,但它正在起作用

private void btnZip_Click(object sender, EventArgs e)
    {
        //copy location before zipping
        string copytoBeforZippingDirectory = txtBackupToLocation.Text;
        //temporary folder for zipping
        string copytotempDirectory = Path.Combine(copytoBeforZippingDirectory, "Backup_File");
        //where the files are coming from
        string copyfromDirectory = txtBackupFrom.Text;
        //today's date
        string todaysDate = DateTime.Now.ToString("dd_MMM_yyyy");
        //Where the files will end up
        string copytoDirectory = txtBackupToLocation.Text + "\\" + todaysDate + "_backup.zip";

        //Create the new temporary folder for zipping
        Directory.CreateDirectory(copytotempDirectory);

        try
        {
            //Get a list of all files
            string[] fileList = Directory.GetFiles(copyfromDirectory, "*");
            // Copy all files. 
            foreach (string f in fileList)
            {
                // Remove path from the file name. 
                string fName = f.Substring(copyfromDirectory.Length + 1);
                // Use the Path.Combine method to safely append the file name to the path. 
                // Will overwrite if the destination file already exists.
                File.Copy(Path.Combine(copyfromDirectory, fName), Path.Combine(copytotempDirectory, fName), true);
            }
            MessageBox.Show("Files Copied successfully. Beginning Zipping of Files");
        }

        catch (DirectoryNotFoundException dirNotFound)
        {
            MessageBox.Show(dirNotFound.Message);
            Close();
        }
        //Zipping the temporary folder
        try
        {
            ZipFile.CreateFromDirectory(copytotempDirectory, copytoDirectory, CompressionLevel.Optimal, true);
            //Write the current date to the text file
            StreamWriter writer = new StreamWriter(runningDirectory + "\\BackupDate.txt"); //open the file for writing.
            writer.Write(DateTime.Now.ToString("dd MMM yyyy")); //write the current date to the file. change this with your date or something.
            writer.Close(); //remember to close the file again.
            writer.Dispose(); //remember to dispose it from the memory.

            MessageBox.Show("Backup Successful");
        }
        catch (Exception zipException)
        {
            MessageBox.Show(zipException.Message);
        }

        //Remove the temp folder
        try
        {
            Directory.Delete(copytotempDirectory, true);
        }
        catch (Exception)
        {
            MessageBox.Show("Temporary Folder " + copytotempDirectory + " not removed");
        }
    }

最佳答案

首先,要在 C# 中压缩文件,没有比使用第三方应用程序而是使用 Windows 中包含的 powershell zipper 更好的选择了。

无论如何,您必须将文件复制到临时文件,然后压缩临时副本。

关于c# - 即使文件正在使用中,如何在 C# 中压缩文件夹内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26665863/

相关文章:

java - 使用 Java 压缩目录时出现奇怪的结构文件

java - 从 ResourceStream 中提取压缩文件会引发错误 "Invalid stored block lengths"

java - Gradle 无法压缩 .gitignore 和 .gitattributes

c# - GitHub 提交错误 : Permission denied fatal: Unable to process path ~/App_Data/aspnet-MyProject. mdf

c# - 如何将数据集绑定(bind)到具有显示和值成员的下拉列表/组合框

c# - 无法在 asp.net web 应用程序中填充列表框

c# - 根据另一个 DataGridView 的行过滤 BindingSource

c# - 如何删除按钮运行时间?

c# - 如何在MvvmCross中退订弱订阅

c# - 无法使用C#套接字接收字节