无法指定用于 MSDN FileInfo.Copy 示例的目标文件名

Trouble specifying destination filename for use in FileInfo.Copy example from MSDN

我使用两个 DateTimePickers 来指定一个日期范围,然后我使用一个 CheckedListBox 来指定一些带有通配符的文件名字符串,以便在系统环境变量路径中包含的每一天的子目录中枚举。我想使用 FileInfo.Copy 从该源复制到目标。

我的代码已经创建了必要的目录。但是我在指定目标文件名时遇到了问题——它们根本没有按照我写的方式指定。

我正在考虑使用正则表达式,但经过一番挖掘后我发现 this MSDN article 似乎已经可以满足我的要求了。我想我需要修改我的代码才能使用它。我可以使用一些帮助将我已经拥有的内容与 MSDN 在其示例中显示的内容相匹配。

我在我的程序的这一部分已经有一个月了,这让我学到了很多关于 c#、并行编程、异步、lambda 表达式、后台工作者等的知识。看起来应该很简单的东西成为我的大兔子洞。对于这个问题,我只需要在正确的方向上轻推一下,我将不胜感激!

这是我的代码:

    private async void ProcessFiles()
    {

        // create a list of topics
        var topics = topicsBox.CheckedItems.Cast<string>().ToList();

        // create a list of source directories based on date range
        var directories = new List<string>();
        var folders = new List<string>();
        for (DateTime date = dateTimePicker1.Value.Date;
            date.Date <= dateTimePicker2.Value.Date;
            date = date.AddDays(1))
        {
            directories.Add(_tracePath + @"\" + date.ToString("yyyy-MM-dd") + @"\");
            folders.Add(@"\" + date.ToString("yyyy-MM-dd") + @"\");
        }

        // create a list of source files to copy and destination
        // revise based on https://msdn.microsoft.com/en-us/library/kztecsys.aspx?f=255&MSPPError=-2147217396
        foreach (var path in directories)
        {
            var path1 = path;
            try
            {
                foreach (var files2 in folders)
                {
                    // create the target directory
                    var destPath = textBox1.Text + @"\" + textBox4.Text + files2;
                    Console.WriteLine("Target directory is {0}", destPath);
                    Console.WriteLine("Destination filename is {0}", files2);
                    foreach (var files in topics)
                    {
                        foreach (string sourcePath in Directory.EnumerateFiles(path1, files + "*.*", SearchOption.AllDirectories))
                        {
                            // copy the files to the temp folder asynchronously
                            Console.WriteLine("Copy {0} to {1}", sourcePath, destPath);
                            Directory.CreateDirectory(sourcePath.Replace(sourcePath, destPath));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }

所以sourcePath包含源路径和文件名。您可以从中轻松构建目标路径,如下所示:

// Get just the filename of the source file.
var filename = Path.GetFileName(sourcePath);

// Construct a full path to the destination by combining the destination path and the filename.
var fullDestPath = Path.Combine(destPath, filename);

// Ensure the destination directories exist. Don't pass in the filename to CreateDirectory!
Directory.CreateDirectory(destPath);

然后你可以像这样(同步)复制文件:

File.Copy(sourcePath, fullDestPath);