From cf248eef8117ff59ecd132f9d54e842bb68bed82 Mon Sep 17 00:00:00 2001 From: KhasanovAM Date: Fri, 17 Oct 2025 13:51:49 +0400 Subject: [PATCH] Add project files. --- SearchFiles.sln | 34 ++++++ SearchFiles/Program.cs | 161 +++++++++++++++++++++++++ SearchFiles/Program_SearchFilePath.txt | 136 +++++++++++++++++++++ SearchFiles/SearchFiles.csproj | 14 +++ 4 files changed, 345 insertions(+) create mode 100644 SearchFiles.sln create mode 100644 SearchFiles/Program.cs create mode 100644 SearchFiles/Program_SearchFilePath.txt create mode 100644 SearchFiles/SearchFiles.csproj diff --git a/SearchFiles.sln b/SearchFiles.sln new file mode 100644 index 0000000..c8e38d0 --- /dev/null +++ b/SearchFiles.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SearchFiles", "SearchFiles\SearchFiles.csproj", "{55AF452F-1C74-4140-9D9F-249D0113FBF3}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {55AF452F-1C74-4140-9D9F-249D0113FBF3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {55AF452F-1C74-4140-9D9F-249D0113FBF3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {55AF452F-1C74-4140-9D9F-249D0113FBF3}.Debug|x64.ActiveCfg = Debug|Any CPU + {55AF452F-1C74-4140-9D9F-249D0113FBF3}.Debug|x64.Build.0 = Debug|Any CPU + {55AF452F-1C74-4140-9D9F-249D0113FBF3}.Debug|x86.ActiveCfg = Debug|Any CPU + {55AF452F-1C74-4140-9D9F-249D0113FBF3}.Debug|x86.Build.0 = Debug|Any CPU + {55AF452F-1C74-4140-9D9F-249D0113FBF3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {55AF452F-1C74-4140-9D9F-249D0113FBF3}.Release|Any CPU.Build.0 = Release|Any CPU + {55AF452F-1C74-4140-9D9F-249D0113FBF3}.Release|x64.ActiveCfg = Release|Any CPU + {55AF452F-1C74-4140-9D9F-249D0113FBF3}.Release|x64.Build.0 = Release|Any CPU + {55AF452F-1C74-4140-9D9F-249D0113FBF3}.Release|x86.ActiveCfg = Release|Any CPU + {55AF452F-1C74-4140-9D9F-249D0113FBF3}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/SearchFiles/Program.cs b/SearchFiles/Program.cs new file mode 100644 index 0000000..1f51a08 --- /dev/null +++ b/SearchFiles/Program.cs @@ -0,0 +1,161 @@ +using System; +using System.IO; +using System.Diagnostics; +using System.Threading; +using System.Linq; + +class FileDeleter +{ + static int deletedCount = 0; + static int failedCount = 0; + static int skippedCount = 0; + + static void Main(string[] args) + { + Console.WriteLine("Удаление файлов по списку"); + string listFilePath = "results450.txt"; + + if (!File.Exists(listFilePath)) + { + Console.WriteLine("Файл со списком не найден!"); + Console.ReadKey(); + return; + } + + try + { + string[] filesToDelete = File.ReadAllLines(listFilePath) + .Where(f => !string.IsNullOrWhiteSpace(f)) + .ToArray(); + + Console.WriteLine($"Найдено {filesToDelete.Length} файлов для обработки...\n"); + + foreach (string filePath in filesToDelete) + { + ProcessFile(filePath); + } + + Console.WriteLine($"\nИтог:"); + Console.WriteLine($"Успешно удалено: {deletedCount}"); + Console.WriteLine($"Не удалось удалить: {failedCount}"); + Console.WriteLine($"Пропущено (не существует): {skippedCount}"); + } + catch (Exception ex) + { + Console.WriteLine($"Критическая ошибка: {ex.Message}"); + } + + Console.WriteLine("\nНажмите любую клавишу для выхода..."); + Console.ReadLine(); + } + + static void ProcessFile(string filePath) + { + Console.WriteLine($"\nОбработка файла: {filePath}"); + + try + { + if (!File.Exists(filePath)) + { + Console.WriteLine("Файл не существует, пропускаем."); + skippedCount++; + return; + } + + string fileName = Path.GetFileName(filePath); + string? computerName = GetComputerNameFromPath(filePath); + + if (!string.IsNullOrEmpty(computerName)) + { + KillProcessOnRemotePC(computerName, fileName); + } + else + { + KillProcessesUsingFile(filePath); + } + + Thread.Sleep(1000); + + File.SetAttributes(filePath, FileAttributes.Normal); + File.Delete(filePath); + Console.WriteLine("Файл успешно удален."); + deletedCount++; + } + catch (UnauthorizedAccessException) + { + Console.WriteLine("Ошибка: Нет прав доступа к файлу"); + failedCount++; + } + catch (IOException ioEx) + { + Console.WriteLine($"Ошибка ввода/вывода: {ioEx.Message}"); + failedCount++; + } + catch (Exception ex) + { + Console.WriteLine($"Ошибка при удалении файла: {ex.Message}"); + failedCount++; + } + } + + static string? GetComputerNameFromPath(string path) + { + if (path.StartsWith(@"\\")) + { + int endIndex = path.IndexOf('\\', 2); + if (endIndex > 2) + { + return path.Substring(2, endIndex - 2); + } + } + return null; + } + + static void KillProcessesUsingFile(string filePath) + { + string fileName = Path.GetFileNameWithoutExtension(filePath); + foreach (var process in Process.GetProcessesByName(fileName)) + { + try + { + Console.WriteLine($"Завершение процесса {process.ProcessName} (ID: {process.Id})"); + process.Kill(); + process.WaitForExit(3000); + } + catch (Exception ex) + { + Console.WriteLine($"Не удалось завершить процесс: {ex.Message}"); + } + } + } + + public static void KillProcessOnRemotePC(string computerName, string processName) + { + try + { + Console.WriteLine($"Попытка завершить процесс {processName} на компьютере {computerName}"); + + ProcessStartInfo psi = new ProcessStartInfo + { + FileName = "taskkill", + Arguments = $"/S {computerName} /IM {processName} /F", + CreateNoWindow = true, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + + using (Process process = new Process { StartInfo = psi }) + { + process.Start(); + string output = process.StandardOutput.ReadToEnd(); + string error = process.StandardError.ReadToEnd(); + process.WaitForExit(); + } + } + catch (Exception ex) + { + Console.WriteLine($"Ошибка при удаленном завершении процесса: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/SearchFiles/Program_SearchFilePath.txt b/SearchFiles/Program_SearchFilePath.txt new file mode 100644 index 0000000..61ae6b0 --- /dev/null +++ b/SearchFiles/Program_SearchFilePath.txt @@ -0,0 +1,136 @@ +using System.Linq.Expressions; +using System.Net.NetworkInformation; + +class FileSearchProgram +{ + static string resultFilePath = "results.txt"; + + static void Main(string[] args) + { + // Очищаем файл результатов при каждом новом запуске + File.WriteAllText(resultFilePath, $"Поиск файла начат: {DateTime.Now}\n\n"); + + Console.WriteLine("Программа поиска файла в доменных компьютерах"); + LogToFile("Программа поиска файла в доменных компьютерах"); + + string fileName = "Monitoring850.exe"; + string searchPath = "D:\\"; + string computersFile = "computers.txt"; + + try + { + if (!File.Exists(computersFile)) + { + string error = $"Файл {computersFile} не найден. Создайте файл со списком компьютеров."; + Console.WriteLine(error); + LogToFile(error); + return; + } + + string[] computers = File.ReadAllLines(computersFile) + .Where(c => !string.IsNullOrWhiteSpace(c)) + .ToArray(); + + string startMessage = $"Начинаем поиск файла {fileName} в {computers.Length} компьютерах..."; + Console.WriteLine(startMessage); + LogToFile(startMessage); + + foreach (string computer in computers) + { + try + { + if (PingComputer(computer)) + { + string checkingMsg = $"Проверяем компьютер {computer}..."; + Console.WriteLine(checkingMsg); + LogToFile(checkingMsg); + + string uncPath = $"\\\\{computer}\\{searchPath.Replace(":", "$")}"; + + if (Directory.Exists(uncPath)) + { + SearchFiles(uncPath, fileName); + } + else + { + string pathError = $"Путь {uncPath} недоступен на компьютере {computer}"; + Console.WriteLine(pathError); + LogToFile(pathError); + } + } + else + { + string unavailable = $"Компьютер {computer} недоступен"; + Console.WriteLine(unavailable); + LogToFile(unavailable); + } + } + catch (Exception ex) + { + string compError = $"Ошибка при обработке компьютера {computer}: {ex.Message}"; + Console.WriteLine(compError); + LogToFile(compError); + } + } + + string endMessage = $"\nПоиск завершен: {DateTime.Now}"; + Console.WriteLine(endMessage); + LogToFile(endMessage); + } + catch (Exception ex) + { + string fatalError = $"Критическая ошибка: {ex.Message}"; + Console.WriteLine(fatalError); + LogToFile(fatalError); + } + } + + static bool PingComputer(string computerName) + { + try + { + Ping ping = new Ping(); + PingReply reply = ping.Send(computerName, 1000); + return reply.Status == IPStatus.Success; + } + catch + { + return false; + } + } + + static void SearchFiles(string path, string fileName) + { + try + { + foreach (string file in Directory.GetFiles(path, fileName)) + { + string foundMsg = $"Найден файл: {file}"; + Console.WriteLine(foundMsg); + LogToFile(foundMsg); + } + + foreach (string directory in Directory.GetDirectories(path)) + { + SearchFiles(directory, fileName); + } + } + catch (Exception ex) + { + string searchError = $"Ошибка при поиске в {path}: {ex.Message}"; + Console.WriteLine(searchError); + } + } + + static void LogToFile(string message) + { + try + { + File.AppendAllText(resultFilePath, message + Environment.NewLine); + } + catch (Exception ex) + { + Console.WriteLine($"Ошибка при записи в файл результатов: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/SearchFiles/SearchFiles.csproj b/SearchFiles/SearchFiles.csproj new file mode 100644 index 0000000..4f43c40 --- /dev/null +++ b/SearchFiles/SearchFiles.csproj @@ -0,0 +1,14 @@ + + + + Exe + net9.0 + enable + enable + + + + + + +