Мониторинг изменений в папкахC#

Место общения программистов C#
Ответить
Anonymous
 Мониторинг изменений в папках

Сообщение Anonymous »

Мне нужна помощь с одной задачей.
Мне нужно создать приложение, которое отслеживает любые изменения в папках.
Я нашел эту статью в Microsoft и попытался выполнить ее для своих нужд, мне нужно отслеживать любые изменения и то, что делает пользователь, который меняет. но когда я запускаю его на сервере, все изменения происходят от моего имени пользователя, но мне нужно просмотреть, какой пользователь это делает.
Может кто-нибудь помочь решить эту проблему?< /p>
using System;
using System.IO;

namespace MyNamespace
{
class NewClassCS
{
private static string logFilePath;
private static string lastChange;

static void Main()
{
string currentDirectory = Directory.GetCurrentDirectory();

Console.WriteLine($"Monitoring folder: {currentDirectory}");
Console.WriteLine("Enter the path for the log file (or press Enter to use default 'log.txt'):");
string userInput = Console.ReadLine();

// Set default log file path in the current directory if user input is empty
logFilePath = string.IsNullOrWhiteSpace(userInput) ? Path.Combine(currentDirectory, "log.txt") : userInput;

// Check if the log file exists, create it if it doesn't
if (!File.Exists(logFilePath))
{
try
{
using (StreamWriter sw = File.CreateText(logFilePath))
{
sw.WriteLine("Log file created.");
}
}
catch (Exception ex)
{
Console.WriteLine($"Failed to create log file: {ex.Message}");
return;
}
}

using var watcher = new FileSystemWatcher(currentDirectory);

watcher.NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.Security
| NotifyFilters.Size;

// Event handlers for file system changes
watcher.Created += OnCreated;
watcher.Deleted += OnDeleted;
watcher.Renamed += OnRenamed;
watcher.Changed += OnChanged; // Added to handle directory changes
watcher.Error += OnError;

watcher.IncludeSubdirectories = true; // Monitor subdirectories
watcher.EnableRaisingEvents = true; // Enable raising events

Console.WriteLine($"Monitoring folder: {currentDirectory}");
Console.WriteLine($"Logging changes to: {logFilePath}");
Console.WriteLine("Press enter to exit.");

Console.ReadLine(); // Wait for user input
}

private static void WriteToLogFile(string message)
{
try
{
using (StreamWriter writer = new StreamWriter(logFilePath, true))
{
string username = Environment.UserName; // Get current user's name
writer.WriteLine($"{DateTime.Now}: {username} - {message}"); // Include username in the log message
}
}
catch (Exception ex)
{
Console.WriteLine($"Failed to write to log file: {ex.Message}");
}
}

private static void OnCreated(object sender, FileSystemEventArgs e)
{
if (e.FullPath != lastChange)
{
WriteToLogFile($"Created: {e.FullPath}");
lastChange = e.FullPath;
}
}

private static void OnDeleted(object sender, FileSystemEventArgs e)
{
if (e.FullPath != lastChange)
{
WriteToLogFile($"Deleted: {e.FullPath}");
lastChange = e.FullPath;
}
}

private static void OnRenamed(object sender, RenamedEventArgs e)
{
if (e.OldFullPath != lastChange && e.FullPath != lastChange)
{
WriteToLogFile($"Renamed: {e.OldFullPath} -> {e.FullPath}");
lastChange = e.FullPath;
}
}

private static void OnChanged(object sender, FileSystemEventArgs e)
{
if (e.FullPath != lastChange)
{
WriteToLogFile($"Changed: {e.FullPath}");
lastChange = e.FullPath;
}
}

private static void OnError(object sender, ErrorEventArgs e) =>
Console.WriteLine($"Error: {e.GetException().Message}");
}
}


Подробнее здесь: https://stackoverflow.com/questions/782 ... in-folders
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»