在c#中创建目录后复制文件

时间:2013-09-16 16:50:56

标签: c# copy

我的File.Copy(xxx,xxx,true)抛出一个未处理的异常我明白File.copy不允许我使用目录但在我的情况下我的文件名可以在每次循环时改变。我需要的文件名与我的源文件夹中显示的文件名相同。这是我到目前为止所拥有的。有任何想法吗?我查看了MSDN,但它定义了我的问题,而不是解决方案。任何帮助赞赏。

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

1 个答案:

答案 0 :(得分:2)

我认为你的错误是你没有在目的地参数中包含文件名。

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