2015-10-13 77 views
1

我有以下List<String> fileNames獲得通過我的方法, 我希望從刪除子路徑並創建離開了文件結構刪除文件名的子路徑和創建文件結構

string subPath = "C:\\temp\\test" 
List<string> filesIncoming = new List[]{@"C:\temp\test\a.txt", @"C:\temp\test\intest\a.txt"}; 
string outputDir = "C:\\temp3\\temp"; 

輸出應該是:

C:\\temp3\temp\a.txt 
C:\\temp3\temp\intest\a.txt 

這是我想

foreach (var file in files) 
{ 
    var directory = Path.GetDirectoryName(file); 
    DirectoryInfo source = new DirectoryInfo(directory); 

    var fileName = Path.GetFileName(file); 
    var destDir = Path.Combine(destinatonFilePath, source.Name); //how do I remove sub-path from source.Name and combine the paths properly? 
    CreateDirectory(new DirectoryInfo(destDir)); 
    File.Copy(file, Path.Combine(destDir, fileName), true); 
} 

回答

1

我認爲你應該使用舊的良好字符串。替換爲從傳入文件中刪除公共基本路徑,並將其替換爲輸出文件的公共基本路徑

string subPath = "C:\\temp\\test" 
string outputDir = "C:\\temp3\\temp"; 

foreach (var file in files) 
{ 
    // Not sure how do you have named these two variables. 
    string newFilePath = file.Replace(subPath, outputDir); 
    Directory.CreateDirectory(Path.GetDirectoryName(newFilePath)); 
    File.Copy(file, newFilePath, true); 
}