在 c# 中创建目录后复制文件
本文关键字:复制 文件 创建目录 | 更新日期: 2023-09-27 18:31:33
My 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);
}
}
我认为您的错误在于您没有在目标参数中包含文件名。
string filename = Path.GetFileName(s);
string newPath = Path.Combine(result, filename);
File.Copy(s, newPath, true);