Add project files.
This commit is contained in:
34
SearchFiles.sln
Normal file
34
SearchFiles.sln
Normal file
@@ -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
|
||||
161
SearchFiles/Program.cs
Normal file
161
SearchFiles/Program.cs
Normal file
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
136
SearchFiles/Program_SearchFilePath.txt
Normal file
136
SearchFiles/Program_SearchFilePath.txt
Normal file
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
14
SearchFiles/SearchFiles.csproj
Normal file
14
SearchFiles/SearchFiles.csproj
Normal file
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="System.DirectoryServices" Version="9.0.6" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Reference in New Issue
Block a user