简体   繁体   中英

C# Moving Files into Folders if part of the file name matches the folder name

I have .CID files that I want to move into directories if part of the .CID file name matches part of the directory name.

Here are some sample directories:

S002016-P063    // projectnumber-panelnumber
S002016-P066
S002016-P067

Here are some sample file names:

P063-1.LEFT.CID    // move to S002016-P063 directory
P063-10.RIGHT.CID    // move to S002016-P063 directory
P066-2_P066-5.LEFT.CID    // move to S002016-P066 because P066 == P066
P067-12.LEFT.CID    // move to S002016-P067
P067-5_P063-2.RIGHT.CID    // leave file where it’s at because P067 != P063

Right now I physically move these files into the appropriate directory but I assume it can be done using a console application. I'm wondering if the I need to set up some if statements using the Regular Expression Class and maybe the match method? I'm new to C# and would like some help getting started. Here is what I have so far. Basically the console app will list the directories and files in the specified directory.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello and Welcome to the File Sorting Program"); // Displays Text in Quotes

        Console.WriteLine(); // Adds a Space  

        string[] fileEntries = Directory.GetDirectories(@"\\Users\none\Documents\File Sorter"); // Regex for panel number = -([A-Z0-9a-z\-]+)

        System.Console.WriteLine("Directories in the Folder: ");

        Console.WriteLine(); // Adds a Space

        foreach (string fileName in fileEntries)  
        {
            Console.WriteLine(Path.GetFileName(fileName)); // Lists the directories found in the "File Sorter" directory
        }

        Console.WriteLine(); // Adds a Space
        Console.WriteLine(); // Adds a Space

        string[] files = Directory.GetFiles(@"\\Users\none\Documents\File Sorter", "*.CID"); // Regex for panel number = ([A-Z0-9a-z\-]+)-

        System.Console.WriteLine("Files in this Folder: "); // Displays Text in Quotes

        Console.WriteLine(); // Adds a Space

        foreach (string file in files)
        {
            Console.WriteLine(System.IO.Path.GetFileNameWithoutExtension(file)); // Lists each file minus .CID found in the "File Sorter" directory
        }

        Console.WriteLine("Press any key to exit."); // Displays Text in Quotes

        System.Console.ReadKey();       
    }
}

Assuming your folder name and file name pattern is consistent, this should about give you what you're looking for:

string root = @"\\Users\none\Documents\File Sorter";

string[] directories = Directory.GetDirectories(root);
var dirRef = directories.ToDictionary(k => k.Split('-')[1], v => v);

string[] files = Directory.GetFiles(root);
foreach (var file in files)
{
    string fileName = Path.GetFileName(file);
    string projectName = null;
    foreach (Match m in Regex.Matches(fileName, "[A-Za-z0-9]+(?=-)"))
    {
        if (projectName == null)
        {
            projectName = m.Value;
        }
        else if (projectName != m.Value)
        {
            projectName = null;
            break;
        }
    }

    if (projectName == null)
    {
        Console.WriteLine("Project names in file {0} do not match.", fileName);
    }
    else if (dirRef.ContainsKey(projectName))
    {
        File.Move(file, dirRef[projectName] + "\\" + fileName);
        Console.WriteLine("File {0} moved to directory {1}.", fileName, dirRef[projectName]);
    }
    else
    {
        Console.WriteLine("Directory with project name {0} doesn't exist", projectName);
    }
}

I've made some tests and this snippet handles all of the cases above using some Regex . Obviously it can be improved, but it's a starting point for you to work on :)

var projectFolders = Directory.GetDirectories(@"Projects/");
var fileEligibleToBeMoved = new List<string>();

var files = Directory.GetFiles(Directory.GetCurrentDirectory());

foreach (var file in files)
{
    if (!file.Contains(".CID"))
        continue;
    var fileName = Path.GetFileName(file);
    var matches = Regex.Matches(fileName, @"(P[a-zA-Z0-9]+)");

    if (matches.Count == 0)
        continue;

    var isEligible = true;
    var previous = string.Empty;
    foreach (Match match in matches)
    {
        if(previous == string.Empty)
        {
            previous = match.Value;
            continue;
        }
        if (previous != match.Value)
            isEligible = false;
    }
    if (isEligible)
        fileEligibleToBeMoved.Add(file);                
}

foreach (var dir in projectFolders)
{
    var panelTag = Regex.Match(dir, @"-\w+").Value.Replace("-", "");                
    var filesToMove = fileEligibleToBeMoved
        .Where(file => file.Contains(panelTag))
        .ToArray();
    foreach (var file in filesToMove)
    {

        File.Move(file, string.Format("{0}/{1}", dir, Path.GetFileName(file)));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM