2012-02-09 6 views
6

あるフォルダから別のディレクトリにファイルが存在しない場合は、宛先ディレクトリ。フォルダが存在しない場合、そのフォルダを作成して1つのディレクトリから別のディレクトリにファイルをコピーする方法

例:

  • ソースパス:C:\temp\test\1.txt
  • 先のパス:C:\Data\

C:\Data\は "TEMP" または "テスト" フォルダが含まれていない場合、それは前にフォルダを作成する必要があります対処1.txt。以下はC:\Data\temp\test\1.txt

にコピー

は私のコードです。しかし、動作しません..

Private Sub btnBackup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBackup.Click 
      Dim sourcepath As String = "C:\temp\test\1.txt" 
    Dim DestPath As String = "C:\Data\" 
    CopyDirectory(sourcepath, DestPath) 
End Sub 

Private Shared Sub CopyDirectory(sourcePath As String, destPath As String) 
    If Not Directory.Exists(destPath) Then 
     Directory.CreateDirectory(destPath) 
    End If 

    For Each file__1 As String In Directory.GetFiles(sourcePath) 
     Dim dest As String = Path.Combine(destPath, Path.GetFileName(file__1)) 
     File.Copy(file__1, dest) 
    Next 

    For Each folder As String In Directory.GetDirectories(sourcePath) 
     Dim dest As String = Path.Combine(destPath, Path.GetFileName(folder)) 
     CopyDirectory(folder, dest) 
    Next 
End Sub 
+0

すべてのエラー?あなたはXPまたはWindows 7を使用していますか? –

+4

"それは動作しません"のようなフレーズは質問を提出するときにSOによってブロックされるべきです;) –

答えて

9

以下はディレクトリではありません。

Dim sourcepath As String = "C:\temp\test\1.txt" 

Directory.GetFiles(sourcePath)のディレクトリとして使用しているためです。

それ以外にも、次回より質問を詳しく説明することをおすすめします。コードはDirectoryNotFoundExceptionのような意味の例外をメッセージとして、または(ファイルが存在する場合は)IOExceptionのメッセージで"ディレクトリ名が無効"というメッセージで表示します。あなたはそれを質問に追加しておくべきです。

だから、解決策は単純にディレクトリ名から1.txtを削除することです:1つのファイルだけをコピーする必要がある場合は、

Dim sourcepath As String = "C:\temp\test\" 

CopyTo methodを使用します。

Dim sourcepath As String = "C:\temp\test\" 
Dim DestPath As String = "C:\temp\Data\" 
If Not Directory.Exists(DestPath) Then 
    Directory.CreateDirectory(DestPath) 
End If 
Dim file = New FileInfo("C:\temp\test\1.txt") 
file.CopyTo(Path.Combine(DestPath, file.Name), True) 
+0

私はテキストファイルをたくさん持っていますが、私は1.txtファイルのみをコピーします。 – user1101157

+0

@ user1101157:私の答えが更新されました。 –

0
Dim strMasterResourceDirectory As String 
    Dim strDirectory As String 

    strDirectory = "C:\TestDestination" 
    strMasterResourceDirectory = "TestResource" 

    If My.Computer.FileSystem.DirectoryExists(strDirectory) = False Then 
     My.Computer.FileSystem.CreateDirectory(strDirectory) 
    End If 

    ' Loop through each file in the directory 
    For Each file As IO.FileInfo In New IO.DirectoryInfo(strDirectory).GetFiles 

     If file.Name <> "Thumbs.db" Then 

      System.IO.File.Delete(strDirectory & "\" & file.Name) 

     End If 
    Next 

    ' Loop through each file in the directory 
    For Each file As IO.FileInfo In New IO.DirectoryInfo(strMasterResourceDirectory).GetFiles 

     If file.Name <> "Thumbs.db" Then 

      ' copy resource to users local directory 

      file.CopyTo(strDirectory & "\" & file.Name) 

     End If 
    Next 
+0

ようこそStackOverflowへ!コードに少し説明を加えてください。ありがとうございました! – Aurasphere

関連する問題