Мне нужна помощь с одной задачей.
Мне нужно создать приложение, которое отслеживает любые изменения в папках.
Я нашел эту статью в 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
Мониторинг изменений в папках ⇐ C#
Место общения программистов C#
1712655136
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}");
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/78297449/monitoring-changes-in-folders[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия