2011-09-09 49 views
2

我想使用C#.NET將目錄從一個位置移動到另一個位置。我用Directory.Move甚至DirectoryInfo的(與通過MoveTo)這個簡單的方法:將文件夾(目錄)從一個位置移動到另一個位置 - 行爲不端

// source is: "C:\Songs\Elvis my Man" 
// newLocation is: "C:\Songs\Elvis" 

try 
{ 
    // Previous command was: Directory.Move(source, newLocation); 
    DirectoryInfo dir = new DirectoryInfo(source); 
    dir.MoveTo(newLocation); 
} 
catch (Exception e) 
{ 
    Console.WriteLine("Error: "+ e.Message); 
} 

但行動應該正在做(這兩種情況下)被重命名的文件夾名稱從「源」到「newLocation」

我的預期是什麼?那個文件夾「Elvis my man」現在會在「Elvis」文件夾中。

發生了什麼事?「貓王我的男人」改爲「貓王」(改名)。如果目錄「Elvis」已經存在,它不能將其更改爲「Elvis」(因爲他不能重複名稱),所以我得到一個異常說。

我在做什麼錯?

非常感謝!

回答

3

即使這部作品在命令行中移動文件,編程你什麼時候需要提供完整的新名字。

因此,您需要將newLocation更改爲「C:\ Songs \ Elvis \ Elvis my man」才能完成此項工作。

2

MSDN

此方法拋出IOException如果,例如,您嘗試移動C:\ MYDIR到c:\公衆和c:\公衆已經存在。您必須指定「c:\ public \ mydir」作爲destDirName參數,或者指定一個新的目錄名稱,例如「c:\ newdir」。

看起來你需要設置newLocation到C:\歌曲\貓王\貓王我的男人

4

我會建議對移動命令進行驗證,以確保源位置確實存在,並且目標位置不存在。

我總是發現避免異常比處理它們更容易,一旦它們發生。

你可能會想包括異常處理爲好,以防萬一的訪問權限是一個問題或一個文件是開放的,不能移動...

下面是一些對你的代碼示例:

  string sourceDir = @"c:\test"; 
     string destinationDir = @"c:\test1"; 

     try 
     { 
      // Ensure the source directory exists 
      if (Directory.Exists(sourceDir) == true) 
      { 
       // Ensure the destination directory doesn't already exist 
       if (Directory.Exists(destinationDir) == false) 
       { 
        // Perform the move 
        Directory.Move(sourceDir, destinationDir); 
       } 
       else 
       { 
        // Could provide the user the option to delete the existing directory 
        // before moving the source directory 
       } 
      } 
      else 
      { 
       // Do something about the source directory not existing 
      } 
     } 
     catch (Exception) 
     { 
      // TODO: Handle the exception that has been thrown 
     } 
相關問題