2011-09-09 24 views
2

C#.NETを使用してある場所から別の場所にディレクトリを移動したいとします。 「ソース」から「newLocation」ある場所から別の場所にフォルダ(ディレクトリ)を移動する - 誤動作

にフォルダ名をリネームされる(両方のケースのために)行われています

// 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); 
} 

しかしアクション:私はDirectory.Moveか(のMoveToと)でもDirectoryInfoこの単純な方法で使用しました期待したことは?そのフォルダ "Elvis my man"は "Elvis"フォルダにあります。

何が起こったのですか?「Elvis my man」は「Elvis」(名称変更)に変更されました。ディレクトリ "Elvis"が既に存在する場合、 "Elvis"に変更することはできません(名前が重複しないため)、例外が表示されます。

私は何が間違っていますか?

多くの感謝!!!たとえば、あなたが移動しようと、場合

MSDNから

答えて

3

でも、これはあなたをプログラミングする際に、ファイルを移動するには、コマンドラインで動作するものの、完全なを提供する必要があります新しい名前。

このようにするには、newLocationを "C:\ Songs \ Elvis \ Elvis my Man"に変更する必要があります。

2

このメソッドはIOExceptionがスローされます。C:\ MYDIR Cへ:公共\とC:国民がすでに存在している\。 destDirNameパラメーターに "c:¥public¥mydir"を指定するか、 "c:¥newdir"などの新しいディレクトリー名を指定する必要があります。

あなたがCにnewLocationを設定する必要があるように見えます:アルバム\エルビス\エルビス私の男\

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 
     } 
関連する問題