C# 使用通配符复制多个文件并保留文件名

标签 c#

我需要使用不包含完整信息的文本文件从目录复制多个文件。

NCR.txt:
红色

目标目录中有:
red1.txt
red3.txt
red44.txt

dest目录需要有:
red1.txt
red3.txt
red44.txt

我的代码:

System.IO.Directory.CreateDirectory(@"C:\nPrep\" + textBox1.Text + "\\red");
        if (checkBox3.Checked)
        {
            String[] file_names = File.ReadAllLines(@"C:\NCR.txt");

            foreach (string file_name in file_names)
            {
                string[] files = Directory.GetFiles(textBox2.Text, file_name + "*.txt");
                foreach (string file in files)
                    System.IO.File.Copy(file, @"C:\nPrep\" + textBox1.Text + "\\red\\");
            }

        }

最佳答案

//FileInfo & DirectoryInfo are in System.IO
//This is something you should be able to tweak to your specific needs.

static void CopyFiles(DirectoryInfo source, 
                      DirectoryInfo destination, 
                      bool overwrite, 
                      string searchPattern)
{
    FileInfo[] files = source.GetFiles(searchPattern);

    //this section is what's really important for your application.
    foreach (FileInfo file in files)
    {
        file.CopyTo(destination.FullName + "\\" + file.Name, overwrite);
    }
}

这个版本更适合复制粘贴:

static void Main(string[] args)
{
    DirectoryInfo src = new DirectoryInfo(@"C:\temp");
    DirectoryInfo dst = new DirectoryInfo(@"C:\temp3");

    /*
     * My example NCR.txt
     *     *.txt
     *     a.lbl
     */
    CopyFiles(src, dst, true);
}

static void CopyFiles(DirectoryInfo source, DirectoryInfo destination, bool overwrite)
{
    List<FileInfo> files = new List<FileInfo>();

    string[] fileNames = File.ReadAllLines("C:\\NCR.txt");

    foreach (string f in fileNames)
    {
        files.AddRange(source.GetFiles(f));
    }

    if (!destination.Exists)
        destination.Create();

    foreach (FileInfo file in files)
    {
        file.CopyTo(destination.FullName + @"\" + file.Name, overwrite);
    }
}

关于C# 使用通配符复制多个文件并保留文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1835578/

相关文章:

c# - 使用 Linq 检查元组列表是否包含一个元组,其中 Item1 = x

c# - GridView 中的更新行不起作用

c# - 如何更改/设置从 TLB (TLH) 中的 EventArgs 继承的 COM 类的 GUID

c# - 如何在自动映射器中使用模式映射源和目的地?

c# - C sharp "public IntPtr pHandle = IntPtr.Zero;"相当于 Delphi "hp: Pointer"

c# - 卡在 SqlDataReader.GetValues 方法上

c# - Form.Owner - 拥有的表单不递归关闭/隐藏

c# - .NET 中的对象引用有多大?

c# - EF 6 将 Where 子句添加到包含导航属性

c# - 使用 SQLite ADO.Net Provider 需要在不使用参数的情况下将 GUID 直接放入查询的 Where 子句中