Чтобы создать C# код для сканирования всех файлов на всех дисках на наличие определенного текста, можно написать консольное приложение, которое рекурсивно просматривает каждый файл и ищет в нем заданный текст. Вот пример такого кода:
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
public class ScannerFiles
{
public static void ScanAllDrives(string searchText)
{
foreach (var drive in DriveInfo.GetDrives())
{
try
{
if (drive.IsReady)
{
Console.WriteLine($"Scanning drive {drive.Name}");
ScanDirectory(drive.RootDirectory.FullName, searchText);
}
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine($"Access denied to drive {drive.Name}: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Error scanning drive {drive.Name}: {ex.Message}");
}
}
}
private static void ScanDirectory(string path, string searchText)
{
try
{
var fileEntries = Directory.GetFiles(path);
foreach (var fileName in fileEntries)
{
ScanFile(fileName, searchText);
}
var subdirectoryEntries = Directory.GetDirectories(path);
foreach (string subdirectory in subdirectoryEntries)
ScanDirectory(subdirectory, searchText);
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine($"Access denied to folder {path}: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Error scanning folder {path}: {ex.Message}");
}
}
private static void ScanFile(string filePath, string searchText)
{
try
{
// This assumes that the file is not too large to fit into memory
// For large files, you would need to read chunks of data and perform the search.
string content = File.ReadAllText(filePath);
if (content.Contains(searchText))
{
Console.WriteLine($"Text found in file: {filePath}");
}
}
catch (FileNotFoundException)
{
// If file is deleted by a concurrent process
}
catch (UnauthorizedAccessException)
{
// If access to file is denied
}
catch (Exception ex)
{
// Could be an IOException, OutOfMemoryException, or any other exception thrown by File.ReadAllText
Console.WriteLine($"Error reading file {filePath}: {ex.Message}");
}
}
}
Чтобы использовать ScannerFiles с кнопкой, предположим, что у вас есть Windows Forms приложение. Вот как это может выглядеть на Windows Forms:
using System;
using System.Windows.Forms;
public partial class ScannerForm : Form
{
public ScannerForm()
{
InitializeComponent();
// Создаем и настраиваем кнопку
Button scanButton = new Button();
scanButton.Text = "Scan";
scanButton.Click += ScanButton_Click;
this.Controls.Add(scanButton);
}
private void ScanButton_Click(object sender, EventArgs e)
{
string searchText = "text to find"; // Текст для поиска
ScannerFiles.ScanAllDrives(searchText);
}
}
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new ScannerForm());
}
}
Обратите внимание, что сканирование всех файлов на всех дисках может занять много времени и может затронуть критически важные системные файлы, поэтому некоторые пути и файлы могут быть защищены и недоступны для чтения без соответствующих разрешений. Выполнение этого кода должно проводиться осторожно и с учетом возможных рисков для системы.