2013-09-16 61 views
-1

我的File.Copy(xxx,xxx,true)拋出未處理的異常我明白File.copy不允許我使用目錄,但在我的情況下,我的文件名可以更改每個我經歷循環。我需要的文件名與我的源文件夾中顯示的文件名相同。這是我到目前爲止。有任何想法嗎?我看着MSDN,但它定義了我的問題,而不是解決方案。任何幫助讚賞。在c#中創建目錄後複製文件

//Get Data from Filename 
string[] files = System.IO.Directory.GetFiles(sourcePath, "Result*.xml"); 
Regex date = new Regex(@"(?<month>[1-9]|[0-2])_(?<day>\d{2})_(?<year>\d{4})", RegexOptions.CultureInvariant); 

foreach (string s in files) 
{ 
    Match m = date.Match(s); 
    if (m.Success) 
    { 
     //Pass Groups to String 
     string month = m.Groups["month"].Value; 
     string day = m.Groups["day"].Value; 
     string year = m.Groups["year"].Value; 

     //Create Dir 
     var paths = new string[] { targetPath, year, month, day }; 
     string result = paths.Aggregate(Path.Combine);       
     Directory.CreateDirectory(result); 

     //Copy file 
     File.Copy(s, result, true);  
    } 
} 
+6

我可以看看我的水晶球,猜猜你的例外是什麼,或者你想告訴我們嗎? 'File.Copy'可能引發8種不同的可能的例外情況 – tnw

+1

當您說File.Copy不允許您使用目錄時,我認爲您會感到困惑 - 它確實如此。您應該通過所有文件的*完整路徑*,而不僅僅是名稱。請參閱下面的答案。 – wilso132

+1

此外,請學習閱讀[文檔](http://msdn.microsoft.com/en-us/library/9706cfs5.aspx)。如果你有,你會注意到'結果'「...不能是一個目錄」,這是你傳遞它的。此外,它有示例顯示使用路徑(我不知道你在哪裏得到它不允許路徑)。 – tnw

回答

2

,我認爲你的錯誤是,你不包括destination參數的文件名。

string filename = Path.GetFileName(s); 
string newPath = Path.Combine(result, filename); 
File.Copy(s, newPath, true); 
+0

它釘在頭上先生。謝謝。 – willkk