简体   繁体   English

C#文件复制回滚

[英]C# File Copy Rollback

Does anyone know how to implement a rollback function in file copying when an exception is thrown. 有人知道如何在抛出异常时在文件复制中实现回滚功能。

Here are some conditions when I copy the files: 以下是复制文件时的一些条件:

  1. Copy the file to a shared folder 将文件复制到共享文件夹
  2. File is no greater than 3MB 文件大小不超过3MB
  3. File is an image file (jpg, jpeg, bmp, gif, png) 文件是图像文件(jpg,jpeg,bmp,gif,png)
  4. Prevention of file name duplicate is already implemented 已经实现了防止文件名重复
  5. OS is in Windows XP and higher 操作系统在Windows XP及更高版本中
  6. Code is on C# .Net 4.0 in Visual Studio 2010 Professional 代码在Visual Studio 2010 Professional中的C#.Net 4.0上
  7. Network connection is Local Area Network 网络连接是局域网
  8. Multiple files to copy, rollback when an exception is thrown 要复制的多个文件,在抛出异常时回滚

Please help. 请帮忙。 Thanks in advance. 提前致谢。

Yes. 是。 Go back and delete all the files. 返回并删除所有文件。

Depending on your structure, there are a variety of things you can do. 根据您的结构,您可以执行各种操作。 If you have a List<string> , for example, iterate using an int : 例如,如果你有一个List<string> ,则使用int迭代:

for(int i = 0; i < filesToCopy.Count; i++) {
    try {
        // Copy the file
    } catch(Exception ex) {
        // Rollback
        while(--i >= 0) {
            System.IO.File.Delete(filesToCopy[i]); // For example
        }

        break;
    }
}

You can keep track of files copied successfully and delete every one of them when you decide to rollback. 您可以跟踪成功复制的文件,并在您决定回滚时删除它们中的每一个。 However, have you thought that your ability to modify files on the share in general (including deleting them during rollback) is dependent on the network connection? 但是,您是否认为您在共享上修改文件的能力(包括在回滚期间删除它们)取决于网络连接?

In other words, you will never be able to rollback if the exception is due to the network going down -- unless there is another program under your control running on the other side that you can cooperate with. 换句话说,如果异常是由于网络故障导致的,那么你永远无法回滚 - 除非您控制另一方运行的另一个程序可以与您合作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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