开发者

Change file address

suppose we have c:\\d1\\d2\\d3\\... where there are many files and directories in d3.

we want to move all items in d3 to c:\\d1\\new\\.

开发者_JAVA百科how to do it clean and safe?

c:\\d1\\new exists!


If c:\d1\new does not exist yet, and you don't want to keep an empty c:\d1\d2\d3 folder afterward, you can use the Directory.Move() method:

using System.IO;

try {
    Directory.Move(@"c:\d1\d2\d3", @"c:\d1\new");
} catch (UnauthorizedAccessException) {
    // Permission denied, recover...
} catch (IOException) {
    // Other I/O error, recover...
}

If c:\d1\new does exist, you'll have to iterate over the contents of c:\d1\d2\d3 and move its files and folders one by one:

foreach (string item in Directory.GetFileSystemEntries(@"c:\d1\d2\d3")) {
    string absoluteSource = Path.Combine(@"c:\d1\d2\d3", item);
    string absoluteTarget = Path.Combine(@"c:\d1\new", item);
    if (File.GetAttributes(absoluteSource) & FileAttributes.Directory != 0) {
        Directory.Move(absoluteSource, absoluteTarget);
    } else {
        File.Move(absoluteSource, absoluteTarget);
    }
}


Use Directory.Move

Also, MSDN has a handy table of what functions to use for Common I/O Tasks which is a good reference for questions like this.


try
{
    System.IO.Directory.Move(@"c:\d1\d2\d3\", @"c:\d1\new\");
}
catch(...)
{
}

The Move method can throw any of the following exceptions that depending on your usage may or may not be thrown. So you need to code the exception handler in a manner that suits your application.

  • System.IO.IOExeption
  • System.UnauthorizedAccessException
  • System.ArgumentException
  • System.ArgumentNullException
  • System.IO.PathToLongException
  • System.IO.DirectoryNotFoundException

As an general example (you probably don't want/need to display message boxes on errors):

try
{
    System.IO.Directory.Move(@"c:\d1\d2\d3\", @"c:\d1\new\");
}
catch (System.UnauthorizedAccessException)
{
    MessageBox.Show("You do not have access to move this files/directories");
}
catch(System.IO.DirectoryNotFoundException)
{
    MessageBox.Show("The directory to move files/directories from was not found")
}
catch
{
    MessageBox.Show("Something blew up!");
}

Finally, it is worth mentioning that the call to Move will block the current thread until the move is complete. So if you are doing this from a UI it will block the UI until the copy is complete. This might take some time depending on how many files/directories are being move. Therefore it might be prudent to run this in a seperate thread and/or display a cycling progress bar.


Use Directory.Move.

Moves a file or a directory and its contents to a new location.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜