Explore / Programming Выполни данные задачи как проекты C#. Выведи полный код для всех файлов во всех… Save Share Download ▾ ReportВыполни данные задачи как проекты C#. Выведи полный код для всех файлов во всех проектах. Для задач которые говорят "Добавьте к X заданию" выводи только финальный вариант проекта, который исполняет все задачи.
"
Задание 1
Создайте оконное Forms приложение, использующее механизм задач (класс Task). Пользователь вводит в текстовое
поле некоторый текст. По нажатию на кнопку приложение
должно проанализировать текст и вывести отчет. Отчёт
содержит информацию о:
■ Количестве предложений;
■ Количестве символов;
■ Количестве слов;
■ Количестве вопросительных предложений;
■ Количестве восклицательных предложений.
Отчёт в зависимости от выбора пользователя отображается на экране или сохраняется в файл.
Задание 2
Добавьте к первому заданию возможность остановки
и повторного запуска анализа текста
Задание 3
Добавьте к первому заданию возможность выбора типа информации, помещаемой в отчёт. Например,
пользователь может выбрать, что его интересует только
количество предложений и слов.
Задание 4
Создайте оконное Forms приложение, использующее механизм
задач (класс Task). Пользователь вводит путь к директории источнику и директории приёмнику. Приложение
проверяет источник на наличие файлов двойников. Все
оригинальные файлы переносятся в приёмник.
Задание 5
Добавьте к четвертому заданию возможность генерации отчёта о проделанных действиях.
"
Assistant2025-04-26 18:48 UTC Copy response
Copy first prompt Copy first response
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language ru
Conversation date Apr 26, 2025
Added to archive Nov 16, 2026
ID 01m7h42pvxvevzknrz6msr1yrkSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 70080d83b219266122d80a574fdec75d
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
Ниже приводится полный финальный код для всех заданий (1-5), где первые три задания объединены в одно Forms-приложение с анализом текста, а последние два задания — во втором Forms-приложении по работе с файлами (поиск дубликатов и перенос).
Проект 1: TextAnalyzer
Назначение: Анализ текста с возможностью выбора количества статистических данных, запуска/остановки анализа, вывода отчёта на экран или в файл.
Структура файлов:
Form1.cs
Form1.Designer.cs
Program.cs
TextAnalyzer/Program.cs
csharp Copy code
using System;
using System.Windows.Forms;
namespace TextAnalyzer
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
TextAnalyzer/Form1.Designer.cs
csharp Copy code
namespace TextAnalyzer
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBoxInput = new System.Windows.Forms.TextBox();
this.buttonStart = new System.Windows.Forms.Button();
this.buttonStop = new System.Windows.Forms.Button();
this.groupBoxOptions = new System.Windows.Forms.GroupBox();
this.checkBoxExclamations = new System.Windows.Forms.CheckBox();
this.checkBoxQuestions = new System.Windows.Forms.CheckBox();
this.checkBoxWords = new System.Windows.Forms.CheckBox();
this.checkBoxChars = new System.Windows.Forms.CheckBox();
this.checkBoxSentences = new System.Windows.Forms.CheckBox();
this.radioButtonDisplay = new System.Windows.Forms.RadioButton();
this.radioButtonFile = new System.Windows.Forms.RadioButton();
this.label1 = new System.Windows.Forms.Label();
this.richTextBoxReport = new System.Windows.Forms.RichTextBox();
this.groupBoxOptions.SuspendLayout();
this.SuspendLayout();
//
// textBoxInput
//
this.textBoxInput.AcceptsReturn = true;
this.textBoxInput.AcceptsTab = true;
this.textBoxInput.Location = new System.Drawing.Point(12, 33);
this.textBoxInput.Multiline = true;
this.textBoxInput.Name = "textBoxInput";
this.textBoxInput.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBoxInput.Size = new System.Drawing.Size(460, 150);
this.textBoxInput.TabIndex = 0;
//
// buttonStart
//
this.buttonStart.Location = new System.Drawing.Point(12, 189);
this.buttonStart.Name = "buttonStart";
this.buttonStart.Size = new System.Drawing.Size(100, 30);
this.buttonStart.TabIndex = 1;
this.buttonStart.Text = "Запустить";
this.buttonStart.UseVisualStyleBackColor = true;
this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
//
// buttonStop
//
this.buttonStop.Enabled = false;
this.buttonStop.Location = new System.Drawing.Point(118, 189);
this.buttonStop.Name = "buttonStop";
this.buttonStop.Size = new System.Drawing.Size(100, 30);
this.buttonStop.TabIndex = 2;
this.buttonStop.Text = "Остановить";
this.buttonStop.UseVisualStyleBackColor = true;
this.buttonStop.Click += new System.EventHandler(this.buttonStop_Click);
//
// groupBoxOptions
//
this.groupBoxOptions.Controls.Add(this.checkBoxExclamations);
this.groupBoxOptions.Controls.Add(this.checkBoxQuestions);
this.groupBoxOptions.Controls.Add(this.checkBoxWords);
this.groupBoxOptions.Controls.Add(this.checkBoxChars);
this.groupBoxOptions.Controls.Add(this.checkBoxSentences);
this.groupBoxOptions.Location = new System.Drawing.Point(12, 225);
this.groupBoxOptions.Name = "groupBoxOptions";
this.groupBoxOptions.Size = new System.Drawing.Size(210, 140);
this.groupBoxOptions.TabIndex = 3;
this.groupBoxOptions.TabStop = false;
this.groupBoxOptions.Text = "Выберите информацию для отчёта";
//
// checkBoxExclamations
//
this.checkBoxExclamations.AutoSize = true;
this.checkBoxExclamations.Checked = true;
this.checkBoxExclamations.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxExclamations.Location = new System.Drawing.Point(7, 112);
this.checkBoxExclamations.Name = "checkBoxExclamations";
this.checkBoxExclamations.Size = new System.Drawing.Size(136, 21);
this.checkBoxExclamations.TabIndex = 4;
this.checkBoxExclamations.Text = "Восклицательные";
this.checkBoxExclamations.UseVisualStyleBackColor = true;
//
// checkBoxQuestions
//
this.checkBoxQuestions.AutoSize = true;
this.checkBoxQuestions.Checked = true;
this.checkBoxQuestions.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxQuestions.Location = new System.Drawing.Point(7, 85);
this.checkBoxQuestions.Name = "checkBoxQuestions";
this.checkBoxQuestions.Size = new System.Drawing.Size(146, 21);
this.checkBoxQuestions.TabIndex = 3;
this.checkBoxQuestions.Text = "Вопросительные";
this.checkBoxQuestions.UseVisualStyleBackColor = true;
//
// checkBoxWords
//
this.checkBoxWords.AutoSize = true;
this.checkBoxWords.Checked = true;
this.checkBoxWords.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxWords.Location = new System.Drawing.Point(7, 58);
this.checkBoxWords.Name = "checkBoxWords";
this.checkBoxWords.Size = new System.Drawing.Size(83, 21);
this.checkBoxWords.TabIndex = 2;
this.checkBoxWords.Text = "Слова";
this.checkBoxWords.UseVisualStyleBackColor = true;
//
// checkBoxChars
//
this.checkBoxChars.AutoSize = true;
this.checkBoxChars.Checked = true;
this.checkBoxChars.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxChars.Location = new System.Drawing.Point(7, 31);
this.checkBoxChars.Name = "checkBoxChars";
this.checkBoxChars.Size = new System.Drawing.Size(107, 21);
this.checkBoxChars.TabIndex = 1;
this.checkBoxChars.Text = "Символы";
this.checkBoxChars.UseVisualStyleBackColor = true;
//
// checkBoxSentences
//
this.checkBoxSentences.AutoSize = true;
this.checkBoxSentences.Checked = true;
this.checkBoxSentences.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBoxSentences.Location = new System.Drawing.Point(7, 4);
this.checkBoxSentences.Name = "checkBoxSentences";
this.checkBoxSentences.Size = new System.Drawing.Size(96, 21);
this.checkBoxSentences.TabIndex = 0;
this.checkBoxSentences.Text = "Предложения";
this.checkBoxSentences.UseVisualStyleBackColor = true;
//
// radioButtonDisplay
//
this.radioButtonDisplay.AutoSize = true;
this.radioButtonDisplay.Checked = true;
this.radioButtonDisplay.Location = new System.Drawing.Point(255, 225);
this.radioButtonDisplay.Name = "radioButtonDisplay";
this.radioButtonDisplay.Size = new System.Drawing.Size(167, 21);
this.radioButtonDisplay.TabIndex = 4;
this.radioButtonDisplay.TabStop = true;
this.radioButtonDisplay.Text = "Показать на экране";
this.radioButtonDisplay.UseVisualStyleBackColor = true;
//
// radioButtonFile
//
this.radioButtonFile.AutoSize = true;
this.radioButtonFile.Location = new System.Drawing.Point(255, 252);
this.radioButtonFile.Name = "radioButtonFile";
this.radioButtonFile.Size = new System.Drawing.Size(216, 21);
this.radioButtonFile.TabIndex = 5;
this.radioButtonFile.Text = "Сохранить отчёт в файл (result.txt)";
this.radioButtonFile.UseVisualStyleBackColor = true;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(60, 17);
this.label1.TabIndex = 6;
this.label1.Text = "Ввод текста:";
//
// richTextBoxReport
//
this.richTextBoxReport.Location = new System.Drawing.Point(255, 280);
this.richTextBoxReport.Name = "richTextBoxReport";
this.richTextBoxReport.ReadOnly = true;
this.richTextBoxReport.Size = new System.Drawing.Size(217, 85);
this.richTextBoxReport.TabIndex = 7;
this.richTextBoxReport.Text = "";
//
// Form1
//
this.ClientSize = new System.Drawing.Size(484, 377);
this.Controls.Add(this.richTextBoxReport);
this.Controls.Add(this.label1);
this.Controls.Add(this.radioButtonFile);
this.Controls.Add(this.radioButtonDisplay);
this.Controls.Add(this.groupBoxOptions);
this.Controls.Add(this.buttonStop);
this.Controls.Add(this.buttonStart);
this.Controls.Add(this.textBoxInput);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "Form1";
this.Text = "Анализатор текста";
this.groupBoxOptions.ResumeLayout(false);
this.groupBoxOptions.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox textBoxInput;
private System.Windows.Forms.Button buttonStart;
private System.Windows.Forms.Button buttonStop;
private System.Windows.Forms.GroupBox groupBoxOptions;
private System.Windows.Forms.CheckBox checkBoxExclamations;
private System.Windows.Forms.CheckBox checkBoxQuestions;
private System.Windows.Forms.CheckBox checkBoxWords;
private System.Windows.Forms.CheckBox checkBoxChars;
private System.Windows.Forms.CheckBox checkBoxSentences;
private System.Windows.Forms.RadioButton radioButtonDisplay;
private System.Windows.Forms.RadioButton radioButtonFile;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.RichTextBox richTextBoxReport;
}
}
TextAnalyzer/Form1.cs
Проект 2: FileDuplicateMover
Назначение:
Пользователь выбирает две папки источника и приёмника
Приложение ищет дубликаты файлов по содержимому в папке источнике
Перемещает оригинальные (уникальные) файлы в папку приёмник
По окончании генерирует отчёт о действиях (сколько файлов перемещено, сколько дубликатов пропущено и т.п.)
Структура файлов:
Form1.cs
Form1.Designer.cs
Program.cs
FileDuplicateMover/Program.cs
csharp Copy code
using System;
using System.Windows.Forms;
namespace FileDuplicateMover
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
FileDuplicateMover/Form1.Designer.cs
FileDuplicateMover/Form1.cs
Инструкции для сборки и запуска
Создайте два отдельных проекта Windows Forms App (.NET Framework или .NET 6/7/8) с именами TextAnalyzer и FileDuplicateMover .
Вставьте соответствующий код для каждого проекта.
Запустите первый проект для анализа текста.
Запустите второй проект для поиска дубликатов и переноса файлов.
Если нужна помощь с объединением проектов или другими деталями — спрашивайте.
Show full message · 841 lines Not yet included in a published release.
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TextAnalyzer
{
public partial class Form1 : Form
{
private CancellationTokenSource _cts;
public Form1()
{
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBoxInput.Text))
{
MessageBox.Show("Введите текст для анализа.", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
buttonStart.Enabled = false;
buttonStop.Enabled = true;
richTextBoxReport.Clear();
_cts = new CancellationTokenSource();
var text = textBoxInput.Text;
var token = _cts.Token;
Task.Run(() =>
{
try
{
// имитация длительной задачи (пример)
for (int i = 0; i < 5; i++)
{
token.ThrowIfCancellationRequested();
Thread.Sleep(200); // имитация работы
}
token.ThrowIfCancellationRequested();
var report = AnalyzeText(text, token);
if (token.IsCancellationRequested)
return;
if (InvokeRequired)
{
Invoke((Action)(() =>
{
ShowOrSaveReport(report);
}));
}
else
{
ShowOrSaveReport(report);
}
}
catch (OperationCanceledException)
{
if (InvokeRequired)
{
Invoke((Action)(() =>
{
richTextBoxReport.Text = "Анализ был остановлен пользователем.";
}));
}
else
{
richTextBoxReport.Text = "Анализ был остановлен пользователем.";
}
}
finally
{
if (InvokeRequired)
{
Invoke((Action)(() =>
{
buttonStart.Enabled = true;
buttonStop.Enabled = false;
}));
}
else
{
buttonStart.Enabled = true;
buttonStop.Enabled = false;
}
}
}, token);
}
private void buttonStop_Click(object sender, EventArgs e)
{
buttonStop.Enabled = false;
_cts?.Cancel();
}
private string AnalyzeText(string text, CancellationToken token)
{
var reportLines = new System.Text.StringBuilder();
bool includeSentences = checkBoxSentences.Checked;
bool includeChars = checkBoxChars.Checked;
bool includeWords = checkBoxWords.Checked;
bool includeQuestions = checkBoxQuestions.Checked;
bool includeExclamations = checkBoxExclamations.Checked;
// Подсчёт предложений:
// Считаем предложения, заканчивающиеся на '.', '?', '!'
// Регулярка для предложений: разделяем текст по символам ., !, ? c учётом пробелов.
string pattern = @"(?<=[.!?])\s+";
var sentences = Regex.Split(text.Trim(), pattern, RegexOptions.Multiline | RegexOptions.Compiled);
int sentenceCount = 0;
int questionCount = 0;
int exclamationCount = 0;
foreach (var s in sentences)
{
string trimmed = s.Trim();
if (string.IsNullOrEmpty(trimmed))
continue;
sentenceCount++;
if (trimmed.EndsWith("?"))
questionCount++;
else if (trimmed.EndsWith("!"))
exclamationCount++;
}
int charCount = text.Length;
// Подсчёт слов (просто слова - последовательности из букв/цифр/подчёркиваний)
var words = Regex.Matches(text, @"\b\w+\b");
int wordCount = words.Count;
if (includeSentences)
reportLines.AppendLine($"Количество предложений: {sentenceCount}");
if (includeChars)
reportLines.AppendLine($"Количество символов: {charCount}");
if (includeWords)
reportLines.AppendLine($"Количество слов: {wordCount}");
if (includeQuestions)
reportLines.AppendLine($"Количество вопросительных предложений: {questionCount}");
if (includeExclamations)
reportLines.AppendLine($"Количество восклицательных предложений: {exclamationCount}");
if (reportLines.Length == 0)
reportLines.AppendLine("Нет выбранной информации для отчёта.");
return reportLines.ToString();
}
private void ShowOrSaveReport(string report)
{
if (radioButtonDisplay.Checked)
{
richTextBoxReport.Text = report;
}
else
{
try
{
File.WriteAllText("result.txt", report);
richTextBoxReport.Text = "Отчёт сохранён в файл result.txt";
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка сохранения файла: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
namespace FileDuplicateMover
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.textBoxSource = new System.Windows.Forms.TextBox();
this.textBoxDestination = new System.Windows.Forms.TextBox();
this.labelSource = new System.Windows.Forms.Label();
this.labelDest = new System.Windows.Forms.Label();
this.buttonBrowseSource = new System.Windows.Forms.Button();
this.buttonBrowseDest = new System.Windows.Forms.Button();
this.buttonStart = new System.Windows.Forms.Button();
this.richTextBoxReport = new System.Windows.Forms.RichTextBox();
this.labelReport = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// textBoxSource
//
this.textBoxSource.Location = new System.Drawing.Point(135, 15);
this.textBoxSource.Name = "textBoxSource";
this.textBoxSource.Size = new System.Drawing.Size(390, 22);
this.textBoxSource.TabIndex = 0;
//
// textBoxDestination
//
this.textBoxDestination.Location = new System.Drawing.Point(135, 50);
this.textBoxDestination.Name = "textBoxDestination";
this.textBoxDestination.Size = new System.Drawing.Size(390, 22);
this.textBoxDestination.TabIndex = 1;
//
// labelSource
//
this.labelSource.AutoSize = true;
this.labelSource.Location = new System.Drawing.Point(12, 18);
this.labelSource.Name = "labelSource";
this.labelSource.Size = new System.Drawing.Size(117, 17);
this.labelSource.TabIndex = 2;
this.labelSource.Text = "Папка источника:";
//
// labelDest
//
this.labelDest.AutoSize = true;
this.labelDest.Location = new System.Drawing.Point(12, 53);
this.labelDest.Name = "labelDest";
this.labelDest.Size = new System.Drawing.Size(117, 17);
this.labelDest.TabIndex = 3;
this.labelDest.Text = "Папка приёмника:";
//
// buttonBrowseSource
//
this.buttonBrowseSource.Location = new System.Drawing.Point(531, 12);
this.buttonBrowseSource.Name = "buttonBrowseSource";
this.buttonBrowseSource.Size = new System.Drawing.Size(40, 27);
this.buttonBrowseSource.TabIndex = 4;
this.buttonBrowseSource.Text = "...";
this.buttonBrowseSource.UseVisualStyleBackColor = true;
this.buttonBrowseSource.Click += new System.EventHandler(this.buttonBrowseSource_Click);
//
// buttonBrowseDest
//
this.buttonBrowseDest.Location = new System.Drawing.Point(531, 47);
this.buttonBrowseDest.Name = "buttonBrowseDest";
this.buttonBrowseDest.Size = new System.Drawing.Size(40, 27);
this.buttonBrowseDest.TabIndex = 5;
this.buttonBrowseDest.Text = "...";
this.buttonBrowseDest.UseVisualStyleBackColor = true;
this.buttonBrowseDest.Click += new System.EventHandler(this.buttonBrowseDest_Click);
//
// buttonStart
//
this.buttonStart.Location = new System.Drawing.Point(15, 85);
this.buttonStart.Name = "buttonStart";
this.buttonStart.Size = new System.Drawing.Size(556, 35);
this.buttonStart.TabIndex = 6;
this.buttonStart.Text = "Начать проверку и перенос";
this.buttonStart.UseVisualStyleBackColor = true;
this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
//
// richTextBoxReport
//
this.richTextBoxReport.Location = new System.Drawing.Point(15, 140);
this.richTextBoxReport.Name = "richTextBoxReport";
this.richTextBoxReport.ReadOnly = true;
this.richTextBoxReport.Size = new System.Drawing.Size(556, 190);
this.richTextBoxReport.TabIndex = 7;
this.richTextBoxReport.Text = "";
//
// labelReport
//
this.labelReport.AutoSize = true;
this.labelReport.Location = new System.Drawing.Point(12, 120);
this.labelReport.Name = "labelReport";
this.labelReport.Size = new System.Drawing.Size(101, 17);
this.labelReport.TabIndex = 8;
this.labelReport.Text = "Отчёт работы:";
//
// Form1
//
this.ClientSize = new System.Drawing.Size(597, 342);
this.Controls.Add(this.labelReport);
this.Controls.Add(this.richTextBoxReport);
this.Controls.Add(this.buttonStart);
this.Controls.Add(this.buttonBrowseDest);
this.Controls.Add(this.buttonBrowseSource);
this.Controls.Add(this.labelDest);
this.Controls.Add(this.labelSource);
this.Controls.Add(this.textBoxDestination);
this.Controls.Add(this.textBoxSource);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "Form1";
this.Text = "Поиск дубликатов и перенос файлов";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox textBoxSource;
private System.Windows.Forms.TextBox textBoxDestination;
private System.Windows.Forms.Label labelSource;
private System.Windows.Forms.Label labelDest;
private System.Windows.Forms.Button buttonBrowseSource;
private System.Windows.Forms.Button buttonBrowseDest;
private System.Windows.Forms.Button buttonStart;
private System.Windows.Forms.RichTextBox richTextBoxReport;
private System.Windows.Forms.Label labelReport;
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FileDuplicateMover
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonBrowseSource_Click(object sender, EventArgs e)
{
using (var fbd = new FolderBrowserDialog())
{
fbd.Description = "Выберите папку-источник";
if (fbd.ShowDialog() == DialogResult.OK)
{
textBoxSource.Text = fbd.SelectedPath;
}
}
}
private void buttonBrowseDest_Click(object sender, EventArgs e)
{
using (var fbd = new FolderBrowserDialog())
{
fbd.Description = "Выберите папку-приёмник";
if (fbd.ShowDialog() == DialogResult.OK)
{
textBoxDestination.Text = fbd.SelectedPath;
}
}
}
private async void buttonStart_Click(object sender, EventArgs e)
{
string src = textBoxSource.Text.Trim();
string dest = textBoxDestination.Text.Trim();
if (!Directory.Exists(src))
{
MessageBox.Show("Папка источника не найдена.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!Directory.Exists(dest))
{
MessageBox.Show("Папка приёмника не найдена.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.Equals(src, dest, StringComparison.OrdinalIgnoreCase))
{
MessageBox.Show("Папка источника и приёмника не должны совпадать.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
buttonStart.Enabled = false;
richTextBoxReport.Clear();
try
{
var report = await Task.Run(() => ProcessFiles(src, dest));
richTextBoxReport.Text = report;
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
buttonStart.Enabled = true;
}
}
private string ProcessFiles(string sourceDir, string destDir)
{
var sb = new StringBuilder();
sb.AppendLine($"Начинается проверка файлов из '{sourceDir}'");
sb.AppendLine($"Файлы будут перемещены в '{destDir}'");
string[] allFiles = Directory.GetFiles(sourceDir, "*", SearchOption.TopDirectoryOnly);
sb.AppendLine($"Всего файлов в источнике: {allFiles.Length}");
// Хэшируем содержимое файлов, чтобы найти дубликаты
var hashToFile = new Dictionary<string, string>();
int movedCount = 0;
int duplicatesCount = 0;
int errorsCount = 0;
using (var sha256 = SHA256.Create())
{
foreach (var filePath in allFiles)
{
try
{
byte[] fileHash = GetFileHash(sha256, filePath);
string hashString = BitConverter.ToString(fileHash).Replace("-", "");
if (!hashToFile.ContainsKey(hashString))
{
// Новый уникальный файл
hashToFile[hashString] = filePath;
string fileName = Path.GetFileName(filePath);
string destPath = Path.Combine(destDir, fileName);
// Если файл с таким именем уже есть в приёмнике, добавим суффикс
destPath = GetUniqueFileName(destPath);
File.Move(filePath, destPath);
sb.AppendLine($"[Перемещён] {fileName}");
movedCount++;
}
else
{
sb.AppendLine($"[Дубликат] {Path.GetFileName(filePath)} - пропущен");
duplicatesCount++;
}
}
catch (Exception ex)
{
sb.AppendLine($"Ошибка с файлом {Path.GetFileName(filePath)}: {ex.Message}");
errorsCount++;
}
}
}
sb.AppendLine();
sb.AppendLine("Работа завершена.");
sb.AppendLine($"Всего перемещено файлов: {movedCount}");
sb.AppendLine($"Всего дубликатов пропущено: {duplicatesCount}");
sb.AppendLine($"Ошибок при обработке файлов: {errorsCount}");
return sb.ToString();
}
private byte[] GetFileHash(SHA256 sha256, string filePath)
{
using (var stream = File.OpenRead(filePath))
{
return sha256.ComputeHash(stream);
}
}
/// <summary>
/// Если файл с таким именем уже существует, добавляет суффикс (1), (2) и т.д.
/// </summary>
private string GetUniqueFileName(string path)
{
if (!File.Exists(path))
return path;
string dir = Path.GetDirectoryName(path);
string fileName = Path.GetFileNameWithoutExtension(path);
string ext = Path.GetExtension(path);
int count = 1;
string newPath;
do
{
string newFileName = $"{fileName}({count}){ext}";
newPath = Path.Combine(dir, newFileName);
count++;
} while (File.Exists(newPath));
return newPath;
}
}
}