AndyF
AndyF

Reputation: 9

C# Move files inside dialog's path

I'm struggling with this basic operation.It will be nice if someone can write a working code.So let's say I got folder "AB" on desktop.Folder AB contains subfolder A and subfolder B.Subfolder A contains A.txt and Subfolder B contains B.txt.I want the user to simply choose folder AB via a browser dialog(I did that already) and then,when he clicks on a checkbox,file A.txt will go on subfolder B and B.txt will go on subfolder A.

Upvotes: 0

Views: 110

Answers (2)

MemoryLeak
MemoryLeak

Reputation: 525

Assuming that you have the folder path for both A and B folders,

 var Afolder = @"D:\AB\A";
 var Bfolder = @"D:\AB\B";
 SwapFolderFiles(Afolder, Bfolder);

Pass the folder path for both A and B to SwapFolderFiles,

 private static void SwapFolderFiles(string AFolder, string BFolder)
    {

        var AFolderfiles = System.IO.Directory.GetFiles(AFolder);
        var BFolderfiles = System.IO.Directory.GetFiles(BFolder);

        MoveFiles(AFolder, BFolder, AFolderfiles);
        MoveFiles(BFolder, AFolder, BFolderfiles);            
    }

    private static void MoveFiles(string sourceFolder, string destinationFolder, string[] folderfiles)
    {
        foreach (var file in folderfiles)
        {
            var filename = file.Substring(file.LastIndexOf("\\")+1);
            var source = System.IO.Path.Combine(sourceFolder, filename);
            var destination = System.IO.Path.Combine(destinationFolder, filename);
            System.IO.File.Move(source, destination);
        }
    }

Upvotes: 0

Prajwal
Prajwal

Reputation: 4000

I will do this for simple folders A and B. You will have to consider the chances of sub-folders as well.

string[] filesA = System.IO.Directory.GetFiles(AsourcePath);
string[] filesB = System.IO.Directory.GetFiles(BsourcePath);
foreach (string s in filesA)
{
     System.IO.File.Move(s, AsourcePath);
}
foreach (string s in filesB)
{
     System.IO.File.Move(s, BsourcePath);
}

Please Note: You will have consider so many scenarios for this including sub-folders, overwriting, existing files or folders etc.

Upvotes: 2

Related Questions