Search code examples
c#winformsvisual-studio-2012startswith

How to (StartsWith) start with 4th letter?


I have a question. I want to copy specific files in 'New folder' to 'Target' folder by clicking a button. In 'New folder' contains various of file with different name. For example: "abcUCU0001", "abbUCA0003", "hhhUCU0012", "aaaUCS0012" and many more. 'New folder' contains more than 1000 files and have same 10 letters in its name. I want to copy 10 files and its name must have "UCU". I don't know how to copy using (startsWith) starting with 4th letter. Sorry for my bad grammar.

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

I expect after click a button, 10 files with name "UCU" will copied to Target folder.


Solution

  • If all the files are in the same directory (no sub-directories), then you can get all files using:

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

    And then just copy them across. For more complex criteria, I would get all the files and use LINQ to filter through.

    Details about the search pattern used

    If there are a lot of files in the folder then it might be more efficient to use the EnumerateFiles method

    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.