简体   繁体   English

以最快的方式将某些文件移动到文件夹吗?

[英]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. 我想将所有*.bk文件从给定路径移入/覆盖到一个文件夹,该文件夹具有其作为名称运行的日期。 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? 但这对于这样的基本任务来说感觉代码太多,是否有办法缩短此代码或使该程序更快?

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. 可以在foreach语句中内联声明迭代变量。

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. 编辑:还应该注意,搜索选项'AllDirectories'最有可能花费更长的时间(取决于from_path目录的内容),请尽可能使用'TopLevelOnly'。

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;

        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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