Bumba
Bumba

Reputation: 333

Move certain files to a folder in the fastest way possible?

I want to move/overwrite all *.bk file from a given path to a folder which has the date of the day it runs as name. I'm currently doing it as below:

string startingPath = @"D:\test\Jobs";
DateTime today = DateTime.Today;
string _date = today.ToString("dd-MM-yyyy");
string newPath = @"D:";
string destPath = newPath + "\\" + _date;
if (!Directory.Exists(newPath + "\\" + _date))
    {
    Directory.CreateDirectory(newPath + "\\" + _date);
    }
string[] files = Directory.GetFiles(startingPath, "*.bk", SearchOption.AllDirectories);

// Move the files and overwrite destination files if they already exist.
foreach (string file in files)
    {
    // Use static Path methods to extract only the file name from the path.
    string fileName = Path.GetFileName(file);
    string destFile = Path.Combine(destPath, fileName);
    if (File.Exists(destFile))
    {
        File.Delete(destFile);
    }
    File.Move(file, destFile);
   }

But this feels too much code for such a basic task, is there a way shorten this code or make this program faster?

Upvotes: 0

Views: 402

Answers (2)

Irvingz
Irvingz

Reputation: 119

A lot of what you have written can be simplified:

void MoveAllBk(string from_path)
{
    string to_path = @"D:\" + Today.ToString("dd-MM-yyyy");
    Directory.CreateDirectory(to_path);
    foreach (string file in Directory.GetFiles(from_path, "*.bk", SearchOption.AllDirectories))
    {
        string new_file = System.IO.Path.Combine(to_path, new System.IO.FileInfo(file).Name);
        if (System.IO.File.Exists(new_file)) { System.IO.File.Delete(new_file); }
        System.IO.File.Move(file, new_file);
    }
}

The new path can be declared in one line.

Create Directory will only do so if the specified path does not exist.

The iteration variables can be declared inline with the foreach statement.

This should speed things up somewhat, and as requested, require less code.

Edit: It should also be noted that search option 'AllDirectories' will most likely take longer (depending on the contents of the from_path directory), use 'TopLevelOnly' if at all possible.

Upvotes: 1

jdweng
jdweng

Reputation: 34429

Here is sample code to recursively go through folders :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication19
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        const string FOLDER = @"c:\temp";
        static XmlWriter writer = null;
        static void Main(string[] args)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;

            writer = XmlWriter.Create(FILENAME, settings);
            writer.WriteStartDocument(true);

            DirectoryInfo info = new DirectoryInfo(FOLDER);
            WriteTree(info);

            writer.WriteEndDocument();
            writer.Flush();
            writer.Close();


        }
        static long WriteTree(DirectoryInfo info)
        {
            long size = 0;
            writer.WriteStartElement("Folder");
            try
            {
                writer.WriteAttributeString("name", info.Name);
                writer.WriteAttributeString("numberSubFolders", info.GetDirectories().Count().ToString());
                writer.WriteAttributeString("numberFiles", info.GetFiles().Count().ToString());
                writer.WriteAttributeString("date", info.LastWriteTime.ToString());


                foreach (DirectoryInfo childInfo in info.GetDirectories())
                {
                    size += WriteTree(childInfo);
                }

            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("Exception Folder : {0}, Error : {1}", info.FullName, ex.Message);
                Console.WriteLine(errorMsg);
                writer.WriteElementString("Error", errorMsg);
            }

            FileInfo[] fileInfo = null;
            try
            {
                fileInfo = info.GetFiles();
            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("Exception FileInfo : {0}, Error : {1}", info.FullName, ex.Message);
                Console.WriteLine(errorMsg);
                writer.WriteElementString("Error", errorMsg);
            }

            if (fileInfo != null)
            {
                foreach (FileInfo finfo in fileInfo)
                {
                    try
                    {
                        writer.WriteStartElement("File");
                        writer.WriteAttributeString("name", finfo.Name);
                        writer.WriteAttributeString("size", finfo.Length.ToString());
                        writer.WriteAttributeString("date", info.LastWriteTime.ToString());
                        writer.WriteEndElement();
                        size += finfo.Length;
                    }
                    catch (Exception ex)
                    {
                        string errorMsg = string.Format("Exception File : {0}, Error : {1}", finfo.FullName, ex.Message);
                        Console.WriteLine(errorMsg);
                        writer.WriteElementString("Error", errorMsg);
                    }
                }
            }

            writer.WriteElementString("size", size.ToString());
            writer.WriteEndElement();
            return size;

        }
    }
}

Upvotes: 0

Related Questions