This commit is contained in:
KhasanovAM
2026-05-15 08:59:18 +04:00
parent cf248eef81
commit f0f3ebbc7c
4 changed files with 241 additions and 262 deletions

View File

@@ -1,161 +1,273 @@
using System;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Linq;
using System.Net.NetworkInformation;
class FileDeleter
class FileSearchProgram
{
static int deletedCount = 0;
static int failedCount = 0;
static int skippedCount = 0;
static string resultFilePath = "results.txt";
static void Main(string[] args)
{
Console.WriteLine("Удаление файлов по списку");
string listFilePath = "results450.txt";
// Очищаем файл результатов при каждом новом запуске
File.WriteAllText(resultFilePath, $"Запуск программы: {DateTime.Now}\n\n");
if (!File.Exists(listFilePath))
{
Console.WriteLine("Файл со списком не найден!");
Console.ReadKey();
return;
}
Console.WriteLine("Программа поиска и удаления папки программы на доменных компьютерах");
LogToFile("Программа поиска и удаления папки программы на доменных компьютерах");
string fileName = "DowntimeClassifier.exe";
string folderToDelete = "";
string searchPath = "D:\\lrpo\\downtimeclassifier";
string computersFile = "computers.txt";
try
{
string[] filesToDelete = File.ReadAllLines(listFilePath)
.Where(f => !string.IsNullOrWhiteSpace(f))
.ToArray();
Console.WriteLine($"Найдено {filesToDelete.Length} файлов для обработки...\n");
foreach (string filePath in filesToDelete)
if (!File.Exists(computersFile))
{
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++;
string error = $"Файл {computersFile} не найден. Создайте файл со списком компьютеров.";
Console.WriteLine(error);
LogToFile(error);
return;
}
string fileName = Path.GetFileName(filePath);
string? computerName = GetComputerNameFromPath(filePath);
string[] computers = File.ReadAllLines(computersFile)
.Where(c => !string.IsNullOrWhiteSpace(c))
.ToArray();
if (!string.IsNullOrEmpty(computerName))
string startMessage = $"Начинаем обработку {computers.Length} компьютеров...";
Console.WriteLine(startMessage);
LogToFile(startMessage);
Console.WriteLine("\nВыберите режим работы:");
Console.WriteLine("1 - Только поиск файла");
Console.WriteLine("2 - Только удаление папки");
Console.WriteLine("3 - Поиск файла + удаление папки");
Console.WriteLine("4 - Только поиск папки");
Console.Write("Введите номер режима (1/2/3/4): ");
string mode = Console.ReadLine()?.Trim() ?? "1";
foreach (string computer in computers)
{
KillProcessOnRemotePC(computerName, fileName);
}
else
{
KillProcessesUsingFile(filePath);
try
{
if (PingComputer(computer))
{
string checkingMsg = $"Проверяем компьютер {computer}...";
Console.WriteLine($"\n{checkingMsg}");
LogToFile(checkingMsg);
string uncPath = $"\\\\{computer}\\{searchPath.Replace(":", "$")}";
if (!Directory.Exists(uncPath))
{
string pathError = $"Путь {uncPath} недоступен на компьютере {computer}";
Console.WriteLine(pathError);
LogToFile(pathError);
continue;
}
// Режим 1 или 3: поиск файла
if (mode == "1" || mode == "3")
{
bool fileFound = SearchFiles(uncPath, fileName);
if (!fileFound)
{
string notFoundMsg = $"Файл {fileName} не найден на компьютере {computer}";
Console.WriteLine(notFoundMsg);
LogToFile(notFoundMsg);
}
}
// Режим 2 или 3: удаление папки
if (mode == "2" || mode == "3")
{
DeleteFolder(uncPath, folderToDelete, computer);
}
// Режим 4: поиск папки
if (mode == "4")
{
bool folderFound = SearchFolder(uncPath, folderToDelete);
if (!folderFound)
{
string notFoundMsg = $"Папка \"{folderToDelete}\" не найдена на компьютере {computer}";
Console.WriteLine(notFoundMsg);
LogToFile(notFoundMsg);
}
}
}
else
{
string unavailable = $"Компьютер {computer} недоступен";
Console.WriteLine(unavailable);
LogToFile(unavailable);
}
}
catch (Exception ex)
{
string compError = $"Ошибка при обработке компьютера {computer}: {ex.Message}";
Console.WriteLine(compError);
LogToFile(compError);
}
}
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++;
string endMessage = $"\nОбработка завершена: {DateTime.Now}";
Console.WriteLine(endMessage);
LogToFile(endMessage);
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка при удалении файла: {ex.Message}");
failedCount++;
string fatalError = $"Критическая ошибка: {ex.Message}";
Console.WriteLine(fatalError);
LogToFile(fatalError);
}
}
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)
static bool PingComputer(string computerName)
{
try
{
Console.WriteLine($"Попытка завершить процесс {processName} на компьютере {computerName}");
Ping ping = new Ping();
PingReply reply = ping.Send(computerName, 1000);
return reply.Status == IPStatus.Success;
}
catch
{
return false;
}
}
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = "taskkill",
Arguments = $"/S {computerName} /IM {processName} /F",
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
static bool SearchFiles(string path, string fileName)
{
try
{
bool found = false;
using (Process process = new Process { StartInfo = psi })
foreach (string file in Directory.GetFiles(path, fileName))
{
process.Start();
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
process.WaitForExit();
found = true;
string foundMsg = $"Найден файл: {file}";
Console.WriteLine(foundMsg);
LogToFile(foundMsg);
}
foreach (string directory in Directory.GetDirectories(path))
{
if (SearchFiles(directory, fileName))
{
found = true;
}
}
return found;
}
catch (Exception ex)
{
string searchError = $"Ошибка при поиске в {path}: {ex.Message}";
Console.WriteLine(searchError);
return false;
}
}
static bool SearchFolder(string path, string folderName)
{
try
{
// Проверяем текущую папку
foreach (string dir in Directory.GetDirectories(path))
{
string dirName = Path.GetFileName(dir);
if (string.Equals(dirName, folderName, StringComparison.OrdinalIgnoreCase))
{
string foundMsg = $"Найдена папка: {dir}";
Console.WriteLine(foundMsg);
LogToFile(foundMsg);
return true;
}
}
// Рекурсивно ищем во вложенных папках
foreach (string dir in Directory.GetDirectories(path))
{
if (SearchFolder(dir, folderName))
{
return true;
}
}
return false;
}
catch (Exception ex)
{
string searchError = $"Ошибка при поиске папки в {path}: {ex.Message}";
Console.WriteLine(searchError);
return false;
}
}
static void DeleteFolder(string basePath, string folderName, string computerName)
{
try
{
string targetFolder = Path.Combine(basePath, folderName);
if (Directory.Exists(targetFolder))
{
Console.WriteLine($"Найдена папка {targetFolder} на компьютере {computerName}. Удаляем...");
LogToFile($"Найдена папка {targetFolder} на компьютере {computerName}. Удаляем...");
Directory.Delete(targetFolder, recursive: true);
string successMsg = $"Папка {folderName} успешно удалена на компьютере {computerName}";
Console.WriteLine(successMsg);
LogToFile(successMsg);
}
else
{
// Если папки нет в корне, ищем её во вложенных папках
bool deleted = false;
foreach (string dir in Directory.GetDirectories(basePath))
{
string subFolder = Path.Combine(dir, folderName);
if (Directory.Exists(subFolder))
{
Console.WriteLine($"Найдена папка {subFolder} на компьютере {computerName}. Удаляем...");
LogToFile($"Найдена папка {subFolder} на компьютере {computerName}. Удаляем...");
Directory.Delete(subFolder, recursive: true);
string successMsg = $"Папка {folderName} успешно удалена на компьютере {computerName} (в {dir})";
Console.WriteLine(successMsg);
LogToFile(successMsg);
deleted = true;
break;
}
}
if (!deleted)
{
string notFoundMsg = $"Папка {folderName} не найдена на компьютере {computerName} (искали в {basePath} и подпапках)";
Console.WriteLine(notFoundMsg);
LogToFile(notFoundMsg);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка при удаленном завершении процесса: {ex.Message}");
string deleteError = $"Ошибка при удалении папки {folderName} на компьютере {computerName}: {ex.Message}";
Console.WriteLine(deleteError);
LogToFile(deleteError);
}
}
static void LogToFile(string message)
{
try
{
File.AppendAllText(resultFilePath, message + Environment.NewLine);
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка при записи в файл результатов: {ex.Message}");
}
}
}

View File

@@ -1,136 +0,0 @@
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}");
}
}
}

View File

@@ -8,7 +8,9 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.DirectoryServices" Version="9.0.6" />
<None Update="computers.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1 @@
izh-w02404