如何(StartsWith)从第 4 个字母开始?

How to (StartsWith) start with 4th letter?

我有一个问题。我想通过单击按钮将 'New folder' 中的特定文件复制到 'Target' 文件夹 。在 'New folder' 中包含各种不同名称的文件。例如:"abcUCU0001""abbUCA0003""hhhUCU0012" , "aaaUCS0012" 等等。 'New folder' 包含超过 1000 个文件 并且其名称中有 10 个相同的字母。我想复制10个文件,文件名必须有"UCU"。我不知道如何使用 (startsWith)4th 字母开头进行复制。 对不起我的语法不好。

private void button1_Click(object sender, EventArgs e)
{
    string FROM_DIR = @"C:\Users\Desktop\Source";
    string TO_DIR = @"C:\Users\Desktop\Target";
    DirectoryInfo diCopyForm = new DirectoryInfo(FROM_DIR);
    DirectoryInfo[] fiDiskfiles = diCopyForm.GetDirectories();
    string filename = "UCU";
    int count = 0;
    foreach (DirectoryInfo newfile in fiDiskfiles)
    {
       try
       {
            if (newfile.Name=="New folder")
            {
                foreach (FileInfo file in newfile.GetFiles())
                {
                    if(file.FullName.StartsWith(filename))
                    {
                        File.Copy(file.FullName, Path.Combine(TO_DIR,file.Name));
                        count++;
                        if (count == 10)
                        {
                            break;
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    MessageBox.Show("success");
}

我希望在单击一个按钮后,名称为 "UCU" 的 10 个文件将复制到目标文件夹。

您可以使用 string.IndexOf:

检查文件名是否在第 4 个位置有 "UCU"
//string filename = "UCU";
if (file.FullName.IndexOf(filename) == 3)

如果所有文件都在同一个目录中(没有子目录),那么你可以使用以下方法获取所有文件:

    //assuming diCopyForm is the new folder reference
    // ? denotes 1 character while * is multiple chars
    var files = diCopyForm.GetFiles("???UCU*"); 

然后将它们复制过来。对于更复杂的条件,我会获取所有文件并使用 LINQ 进行过滤。

Details about the search pattern used

如果文件夹中有很多文件,那么使用EnumerateFiles方法可能更有效

The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.