C# 在您';你做完了吗?或者我可以让它一直打开直到程序运行完毕并关闭它吗?
我正在使用C#中的file watcher类,任何时候创建/修改文件时,我都想将更改写入日志文件。我是否应该在每次通知时打开StreamWriter并写入文件?或者StreamWriter应该是一个成员变量,在程序关闭之前保持打开状态?该程序除了监视特定的子目录并记录更改外,什么也不做C# 在您';你做完了吗?或者我可以让它一直打开直到程序运行完毕并关闭它吗?,c#,C#,我正在使用C#中的file watcher类,任何时候创建/修改文件时,我都想将更改写入日志文件。我是否应该在每次通知时打开StreamWriter并写入文件?或者StreamWriter应该是一个成员变量,在程序关闭之前保持打开状态?该程序除了监视特定的子目录并记录更改外,什么也不做 using System; using System.IO; using System.Security.Permissions; public class Watcher
using System;
using System.IO;
using System.Security.Permissions;
public class Watcher
{
private static string path;
public static void Main()
{
Run();
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
private static void Run()
{
//gets input from user for assigns it to path
// Create a new FileSystemWatcher and set its properties.
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
using (StreamWriter outputFile = File.AppendText(path))
{//write to file with time stamp indicating file watch
//start time
}
watcher.Path = path;
// Watch for changes in LastAccess and LastWrite times, and
// the renaming of files or directories.
watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Changed += OnChanged;
watcher.Created += OnChanged;
watcher.Deleted += OnChanged;
watcher.Renamed += OnRenamed;
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press 'q' to quit the sample.");
while (Console.Read() != 'q') ;
}
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e){
using (StreamWriter outputFile = File.AppendText(path))
{//write to file with time stamp indicating what changed
}
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
}
private static void OnRenamed(object source, RenamedEventArgs e){
using (StreamWriter outputFile = File.AppendText(path))
{//write to file with time stamp indicating what renamed
}
// Specify what is done when a file is renamed.
Console.WriteLine($"File: {e.OldFullPath} renamed to {e.FullPath}");
}
}
我将使用
File.AppendAllText()
并让.NET和操作系统来完成这项工作。如果你一直打开它,如果应用程序崩溃会发生什么?另一种选择是使用现有的日志API,让它完成繁重的工作。由于FileSystemWatcher通常会快速连续生成多个事件,因此打开然后立即关闭它实际上可能会导致文件访问问题。您可以使用某种计时器,在XX秒不活动后关闭文件。您可以将StreamWriter移出到您提到的类级别,以便查看是否需要关闭和/或打开它。问题是:您真的需要保持文件句柄打开所能提供的一点额外性能(如果存在)吗?最多,您的问题是基于意见的。但即使是这样的问题也已经被解决了很多次,到目前为止,流行的观点是,一旦你不再需要你的物品,就立即处理它。在我看来,这个问题结束得有点太匆忙了。指示的副本(很少有权威性)没有处理OP提供的上下文。FileSystemWatcher是一个难以处理的怪物。当然,我们都同意一般规则。如果它实现了Dispose,那么您需要尽快调用Dispose,但可能在这里我们遇到了需要更多参数的情况