简体   繁体   中英

C# : Delete all files or none from two different directories

I am sorry if it is duplicate. Please point me in right direction. I have 2 directories Dir1 and Dir2. I have one file in Dir1 and 2 files in Dir2.

Dir1 
 -Dir1File1.txt

Dir2 
 -Dir2File1.txt
 -Dir2File2.txt

Now I need to delete all files in both Dir1 and Dir2. I need to delete all files or none, ie, if I delete files in Dir1 successfully and when I try to delete files in Dir2 and if something wrong happens then I must rollback my delete in Dir1.

SOLUTION

Instead of creating and deleting temp folders this is what I did. I used dictionary to keep track of my the files fullname and data which I want to delete.

private static void DeleteAllFilesOrNone()
    {
        string featuresFolder = @"C:\SCD_Sample\Dir1";
        string cfxFolder = @"C:\SCD_Sample\Dir2";

        Dictionary<string, string> featuresFileInfo = new Dictionary<string, string>();
        Dictionary<string, string> cfxFileInfo = new Dictionary<string, string>();
        List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();

        bool rollbackFileDeleteNeeded = false;
        try
        {
            DirectoryInfo featuresDir = new DirectoryInfo(featuresFolder);
            foreach (var f in featuresDir.GetFiles())
            {
                string key = f.FullName;
                string xml = System.IO.File.ReadAllText(key);
                featuresFileInfo.Add(key, xml);
            }

            DirectoryInfo cfxDir = new DirectoryInfo(cfxFolder);
            foreach (var f in cfxDir.GetFiles())
            {
                string key = f.FullName;
                string xml = System.IO.File.ReadAllText(key);
                cfxFileInfo.Add(key, xml);
            }

            list.Add(featuresFileInfo);
            list.Add(cfxFileInfo);

            //after this any error happens we need to rollback all deleted files
            rollbackFileDeleteNeeded = true;

            //start deleting files
            foreach(Dictionary<string, string> dict in list)
            {
                foreach (KeyValuePair<string, string> kvp in dict)
                {
                    if (File.Exists(kvp.Key))
                    {
                        //file exists to delete
                        File.Delete(kvp.Key);
                        //throw new Exception();
                    }
                }
            }
            Console.WriteLine("Success");
        }
        catch(Exception ex)
        {
            if (rollbackFileDeleteNeeded == true)
            {
                foreach (Dictionary<string, string> dict in list)
                {
                    foreach (KeyValuePair<string, string> kvp in dict)
                    {
                        if (File.Exists(kvp.Key) == false)
                        {
                            //file doesnot exists
                            System.IO.File.WriteAllText(kvp.Key, kvp.Value);
                        }
                    }
                }
            }
            Console.WriteLine("Rolled back");
        }            
    }

A simple way to "simulate" kind of transactional behavior could be to create two temp-directories and MOVE all files from dir1 to tempdir1 and move all files from dir2 to tempdir2. if both succeed, delete your tempdirs, as you know, there will be no lock on the files.

if any exception occurs during any move operation, just move everything that could be moved so far back to where it was.

Delete both your tempdirs in every case at the end of your operation.

As requested, a bit code here - Sorry I have no Visual Studio at hand, I can't test and code it exactly, I just try to point you in the right direction.

string tempdir1 = Environment.GetSpecialFolder.Temp + "\\tempdir1";
string tempdir2 = Environment.GetSpecialFolder.Temp + "\\tempdir2";
Directory.CreateDirectory(tempdir1); 
Directory.CreateDirectory(tempdir2); 

try 
{
    foreach (string filename in Directory.GetFiles(yourdir1, "*.*"))
    {
        File.Move(filename, tempdir1 + Path.GetFilename(filename));
    }
    foreach (string filename in Directory.GetFiles(yourdir2, "*.*"))
    {
        File.Move(filename, tempdir2 + Path.GetFilename(filename));
    }
} 
catch (Exception ex)
{
    // Do the same foreach loops again, but from tempdir to yourdir
    // to move everything back
}
finally 
{
    Directory.DeleteDirectory(tempdir1);    
    Directory.DeleteDirectory(tempdir2);
}

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