-2

In my project ,I want to move a folder to a destination.Here is my thought. First scenario, I want to check Can I move the folder,If I don't have the permission I will not check the sub-items in the folder. Move action is done. second scenario,If I have the permisson to move the folder,I will check all the sub-items in the folder,then move the items that I can move and leave the items that I can't move. So I don't know How to implement the first scenario.If I catch the unauthorizedaccessexception in the scenario.I may block the second scenario,because in the second scenario,while moving folder,it will also throw the exception if some sub-items can not be moved.Can someone give me some suggestions?

letaoz
  • 21
  • 1
  • Do not check if you *can* move files/folders, just try to do it. See [this answer](http://stackoverflow.com/a/265958/1200847) for more details. – Georg Jung Feb 25 '16 at 02:28
  • So you want to 1) try to move the complete directory and if this fails 2) try to move all contained files one by one. Is this corect? How do you want to handle subdirectories? Do you want the method to work recursively? – Georg Jung Feb 25 '16 at 02:30
  • Yes I want to work recursively,only move the moveable subdirectories while move the complete directory fails. – letaoz Feb 25 '16 at 04:54
  • Then please see my answer. It is not based on recursion but works as you would expect. – Georg Jung Feb 25 '16 at 10:11

1 Answers1

0

I did not test this but it should give you a start:

public static void MoveDirectory(string source, string target)
{
    var delSourceAtEnd = true;
    var sourcePath = source.TrimEnd('\\', ' ');
    var targetPath = target.TrimEnd('\\', ' ');
    var files = Directory.EnumerateFiles(sourcePath, "*", SearchOption.AllDirectories)
                            .GroupBy(Path.GetDirectoryName);
    foreach (var folder in files)
    {
        var failed = false;
        var targetFolder = folder.Key.Replace(sourcePath, targetPath);
        Directory.CreateDirectory(targetFolder);
        foreach (var file in folder)
        {
            var targetFile = Path.Combine(targetFolder, Path.GetFileName(file));
            try
            {
                File.Move(file, targetFile);
            } catch (UnauthorizedAccessException uae)
            {
                failed = true;
                delSourceAtEnd = false;
            }
        }
        if (!failed) Directory.Delete(folder.Key);
    }
    if (delSourceAtEnd) Directory.Delete(source, false);
}

This is heavily based on this answer, which shows different options how you can move a directory manually and handle single files and folders individually.

Community
  • 1
  • 1
Georg Jung
  • 949
  • 10
  • 27
  • If you want to check file permissions though, see the [System.Security.Permissions.FileIOPermission class](https://msdn.microsoft.com/de-de/library/system.security.permissions.fileiopermission(v=vs.110).aspx) – Georg Jung Feb 25 '16 at 02:55