2014-02-17 95 views
0

我試圖從閃存盤複製文件夾到C:目錄。有時它運行正常,但有時會出現錯誤:運行時錯誤'找不到路徑的一部分'E:

Could not find a part of the path E:\Debug\Vip

您對這個問題有什麼想法嗎?這裏是我的代碼:

string source_dir = "E:\\Debug\\Vip"; 
string destination_dir = "C:\\Vip"; 

if (!System.IO.Directory.Exists(destination_dir)) 
{ 
    System.IO.Directory.CreateDirectory(destination_dir); 
} 

// substring is to remove destination_dir absolute path (E:\). 

// Create subdirectory structure in destination  
foreach (string dir in Directory.GetDirectories(source_dir, "*", System.IO.SearchOption.AllDirectories)) 
{ 
    Directory.CreateDirectory(destination_dir + dir.Substring(source_dir.Length)); 

} 

foreach (string file_name in Directory.GetFiles(source_dir, "*.*", System.IO.SearchOption.AllDirectories)) 
{ 
    File.Copy(file_name, destination_dir + file_name.Substring(source_dir.Length), true); 
} 
+0

使用Path.Combine http://msdn.microsoft.com/en-us/library/system .io.path.combine.aspx在創建目錄之前加入兩條路徑。 –

回答

0

使用Path.Combine來加入路徑。

例如

Directory.CreateDirectory(System.IO.Path.Combine(destination_dir,dir.Substring(source_dir.Length))); 
2

使用Path.Combine方法在創建目錄之前加入兩個路​​徑。

string source_dir = "E:\\Debug\\Vip"; 
string destination_dir = "C:\\Vip"; 

if (!System.IO.Directory.Exists(destination_dir)) 
{ 
    System.IO.Directory.CreateDirectory(destination_dir); 
} 

// substring is to remove destination_dir absolute path (E:\). 

// Create subdirectory structure in destination  
foreach (string dir in Directory.GetDirectories(source_dir, "*", System.IO.SearchOption.AllDirectories)) 
{ 
    Directory.CreateDirectory(Path.Combine(destination_dir,dir.Substring(source_dir.Length)); 

} 

foreach (string file_name in Directory.GetFiles(source_dir, "*.*", System.IO.SearchOption.AllDirectories)) 
{ 
    File.Copy(file_name, Path.Combine(destination_dir, file_name.Substring(source_dir.Length), true)); 
} 

我喜歡用下面的方法來所有文件夾和文件複製從SOURCEPATH到的DestinationPath

private static void CopyAll(string SourcePath, string DestinationPath) 
{ 
    string[] directories = System.IO.Directory.GetDirectories(SourcePath, "*.*", SearchOption.AllDirectories); 

    Parallel.ForEach(directories, dirPath => 
    { 
     Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath)); 
    }); 

    string[] files = System.IO.Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories); 

    Parallel.ForEach(files, newPath => 
    { 
     File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath)); 
    }); 
} 
相關問題