HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Is there a better way to search directories for a file or files?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filesearchwaybetterfilesfortheredirectories

Problem

Edit:

The purpose of this method is to search a specific directory for a given file type, ex. (.txt, .pdb, *.exe") then move the file(s) to a given destination directory and delete the original file from the source directory.

Is there a better way to write the following code?:

/// 
/// Moves a specific file type from a given 
/// source directory to a destination directory.
/// 
/// The source directory.
/// The destination directory.
/// Type of file to be moved.
private static void MoveFilesToDirectory(string sourceDir, string destDir, string fileExt)
{
    try
    {
        if ( !Directory.Exists(sourceDir) )
        {
            Console.WriteLine("{0} does not exist.", sourceDir);
            return;
        }

        if ( !Directory.Exists(destDir) )
        {
            Directory.CreateDirectory(destDir);
        }

        foreach ( String dir in Directory.GetDirectories(sourceDir) )
        {
            foreach ( String file in Directory.GetFiles(dir, fileExt) )
            {
                string fileName = Path.GetFileName(file);
                string moveFileTo = Path.Combine(destDir, fileName);

                if ( !File.Exists(moveFileTo) )
                {
                    Directory.Move(file, moveFileTo);
                }

                File.Delete(file);
            }

            MoveFilesToDirectory(dir, destDir, fileExt);
        }
    }
    catch ( IOException ex )
    {
        Console.WriteLine(ex.Message);
    }
}

Solution

static void Main(string[] args)
    {
        String mask = "*.txt";
        String source = @"c:\source\";
        String destination = @"c:\destination\";

        String[] files = Directory.GetFiles(source, mask, SearchOption.AllDirectories);
        foreach (String file in files)
        {
            File.Move(file, destination + new FileInfo(file).Name);
        }
    }


Add in your own directory exists verification logic... but this should be all you need at the core. I haven't verified this code, but these built in functions should do what you want.

Code Snippets

static void Main(string[] args)
    {
        String mask = "*.txt";
        String source = @"c:\source\";
        String destination = @"c:\destination\";

        String[] files = Directory.GetFiles(source, mask, SearchOption.AllDirectories);
        foreach (String file in files)
        {
            File.Move(file, destination + new FileInfo(file).Name);
        }
    }

Context

StackExchange Code Review Q#2101, answer score: 7

Revisions (0)

No revisions yet.