65.9K
CodeProject 正在变化。 阅读更多。
Home

跟踪文件活动

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.52/5 (17投票s)

2008 年 7 月 25 日

GPL3

3分钟阅读

viewsIcon

54591

downloadIcon

1323

它有助于使用 FileSystemWatcher 跟踪/监视文件活动并维护日志,可以使用各种筛选器选项进行查看。

Track File Activites

引言

此应用程序将演示如何有效地使用 FileSystemWatcher。 该应用程序具有足够的灵活性,可供用户配置。 用户需要提供他们想要跟踪的 跟踪路径,并提供另一个 工作路径,每天将在此处维护日志文件。 每天将创建文件夹并维护日志。 这将让用户可以灵活地查看前一天的日志,而不会出现任何麻烦。 请注意,一旦定义了此路径,它将存储在系统注册表中,因此用户不必每次打开应用程序时都输入路径,它将自动从注册表中检索。 用户可以选择是否 跟踪子文件夹。 他/她可以使用各种选项进行 过滤,例如“*.*, *win.*, a*b.c* 等”。 也可以根据用户的需要配置 通知筛选器,例如“文件名、目录名、属性、大小、最后写入时间、最后访问时间、创建时间、安全性”。

跟踪文件活动日志

Track File Activites Log

此窗口有助于查看 TrackFileActivity 每天创建的日志。 通常,每天生成的日志都很大,查看所有这些日志是一项非常繁琐的工作。 用户可以选择基于 事件路径时间 过滤数据。 可以选择“创建”、“更改”、“删除”和“重命名”的事件。 路径可以是任何不区分大小写的 string 。 时间可以在开始时间和结束时间之间进行过滤。 用户还可以选择定义 自动刷新间隔,这将根据提到的间隔自动刷新基于筛选器的日志视图。 如果他/她想手动刷新日志视图,则单击 手动刷新 按钮。 用户可以选择单击列表视图的列来按升序或降序对日志/数据进行排序。 日志视图中的每个日志将按“创建”、“重命名”、“删除”和“更改”分组,这些分组将用颜色表示。 默认情况下,日志视图将显示当前日期,但用户可以选择之前的日期日志文件并查看它们。 为了简单起见,Track File Activities Log 窗口在任何给定时间只能打开一个实例。 这意味着用户不能为 Track File Activities Log 打开多个窗口。 这将为学习者提供一个很好的代码,以使用 user32.dll 处理这些情况。

通知图标

Notify Icon

双击通知图标可以在任何情况下打开 TrackFileActivities 。 用户可以选择右键单击并打开 TrackFileActivities 选项、跟踪文件活动日志或退出应用程序。 退出 TrackFileActivities 时,它将询问确认是否退出应用程序。

Using the Code

SendMessage

此代码演示了如何实现 USER32.dll 并在任何给定时间为单个实例打开任何窗口。

//Declare global variable
private int hwdfrmTrackLog;

//Import this function
[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);

//Display frmTrackLog if the form is not already opened
if (hwdfrmTrackLog == -1)
{
   frmTrackLog objfrmTrackLog = new frmTrackLog(strWorkPath);
   objfrmTrackLog.Disposed += new EventHandler(frmTrackLog_Disposed);
   hwdfrmTrackLog = objfrmTrackLog.Handle.ToInt32();
   objfrmTrackLog.Show();
}        

public void frmTrackLog_Disposed(object sender, EventArgs e)
{
   //When the form is disposed, set the handle back
   hwdfrmTrackLog = -1;
}

注册表

此代码演示了如何在系统注册表键中读/写值。

using Microsoft.Win32;

//Read from Registry Key if value exists
RegistryKey rk = Registry.LocalMachine;
RegistryKey rkOpenTrack = rk.OpenSubKey("SOFTWARE\\" + 
        "TrackFileActivitesSumit\\TrackPath");
if (rkOpenTrack != null)
{
   txtSetPath.Text = rkOpenTrack.GetValue("Path").ToString();
}

//Write value to Registry Key
RegistryKey rk = Registry.LocalMachine;
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
   txtSetPath.Text = folderBrowserDialog.SelectedPath;
   RegistryKey rkCreate = rk.CreateSubKey("SOFTWARE\\" + 
        "TrackFileActivitesSumit\\TrackPath");
   rkCreate.SetValue("Path", txtSetPath.Text);
}

btnStartTracking_Click

此代码演示了如何为 FileSystemWatcher 设置筛选器和通知筛选器以及其他参数。 它还检查并相应地设置其他控件。

private void btnStartTracking_Click(object sender, EventArgs e)
{
  try
  {
     if ((txtSetPath.Text.Length != 0) && (txtWorkPath.Text.Length != 0))
     {
         notifyIcon.Text = "Track File Activites [running]";
         btnStartTracking.Enabled = false;
         btnStopTracking.Enabled = true;

         btnSetPath.Enabled = false;
         btnWorkPath.Enabled = false;
         cmbFilters.Enabled = false;
         chkIncludeSubdirectories.Enabled = false;
         gbNotifyFilter.Enabled = false;

         this.fileSystemWatcher.EnableRaisingEvents = false;
         if (chkAttributes.Checked == true)
         {
             fileSystemWatcher.NotifyFilter = 
                fileSystemWatcher.NotifyFilter | NotifyFilters.Attributes;
         }
         if (chkCreationTime.Checked == true)
         {
             fileSystemWatcher.NotifyFilter = 
                fileSystemWatcher.NotifyFilter | NotifyFilters.CreationTime;
         }
         if (chkDirectoryName.Checked == true)
         {
             fileSystemWatcher.NotifyFilter = 
            fileSystemWatcher.NotifyFilter | NotifyFilters.DirectoryName;
         }
         if (chkFileName.Checked == true)
         {
             fileSystemWatcher.NotifyFilter = 
                fileSystemWatcher.NotifyFilter | NotifyFilters.FileName;
         }
         if (chkLastAccess.Checked == true)
         {
             fileSystemWatcher.NotifyFilter = 
                fileSystemWatcher.NotifyFilter | NotifyFilters.LastAccess;
         }
         if (chkLastWrite.Checked == true)
         {
             fileSystemWatcher.NotifyFilter = 
                fileSystemWatcher.NotifyFilter | NotifyFilters.LastWrite;
         }
         if (chkSecurity.Checked == true)
         {
             fileSystemWatcher.NotifyFilter = 
                fileSystemWatcher.NotifyFilter | NotifyFilters.Security;
         }
         if (chkSize.Checked == true)
         {
              fileSystemWatcher.NotifyFilter = 
                fileSystemWatcher.NotifyFilter | NotifyFilters.Size;
         }

         fileSystemWatcher.Path = txtSetPath.Text;
         fileSystemWatcher.Filter = cmbFilters.Text;
         fileSystemWatcher.IncludeSubdirectories = chkIncludeSubdirectories.Checked;
         fileSystemWatcher.EnableRaisingEvents = true;
     }
     else
     {
          MessageBox.Show("Either of the path is not defined. 
    Please define the path for Track File Activities and Working Path for Log.", 
        "Please define Tracking and
    Working path ...", MessageBoxButtons.OK, MessageBoxIcon.Information);
      }
   }
   catch (ArgumentException ae)
   {
       MessageBox.Show(ae.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }
   catch (Exception ee)
   {
       MessageBox.Show(ee.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }
}

fileSystemWatcher_Renamed

此代码演示了如何为 FileSystemWatcher 实现事件并附加到日志文件中。 它演示了 Rename 事件,该事件与其他事件(即“创建”、“删除”和“更改”)相同。

private void fileSystemWatcher_Renamed(object sender, System.IO.RenamedEventArgs e)
{
   StreamWriter sw = File.AppendText(strWorkPath);
   sw.WriteLine(e.ChangeType + "|" + e.OldFullPath + " to " + e.FullPath + 
        "|" + DateTime.Now.ToLongTimeString());
   sw.Flush();
   sw.Close();
}

DisplayLogInListView

此代码演示了如何实现读取日志文件,将筛选器应用于这些数据,并根据“创建”、“重命名”、“删除”和“更改”对每个日志进行分组,并为其分配颜色。

public void DisplayLogInListView()
{
    try
    {
        timer.Enabled = false;

        if (!File.Exists(txtLogPath.Text.Replace("TrackFileActivities.log", "") +
            "Copy of TrackFileActivities.log"))
        {
            File.Copy(txtLogPath.Text, 
                txtLogPath.Text.Replace("TrackFileActivities.log", "") + 
                    "Copy of TrackFileActivities.log");
        }
        else
        {
            File.Delete(txtLogPath.Text.Replace("TrackFileActivities.log", "") +
                "Copy of TrackFileActivities.log");
            File.Copy(txtLogPath.Text, 
                txtLogPath.Text.Replace("TrackFileActivities.log", "") +
                    "Copy of TrackFileActivities.log");
        }

        listViewLog.Items.Clear();
        Match matchRegEx;
        ListViewItem lvItem;
        string strReadLog = "";
        string[] strReadLogColl;
        TextReader tr = new StreamReader
            (txtLogPath.Text.Replace("TrackFileActivities.log", "") +
                "Copy of TrackFileActivities.log");
        while ((strReadLog = tr.ReadLine()) != null)
        {
            bool boolFlag = false;
            strReadLogColl = strReadLog.Split('|');
            if ((chkCreated.Checked == true) && (strReadLogColl[0] == "Created"))
            {
                matchRegEx = Regex.Match(strReadLogColl[1], txtPath.Text, 
                    RegexOptions.IgnoreCase);
                if (matchRegEx.Success)
                {
                    DateTime dtCompStartTime = Convert.ToDateTime
                        (dtStartTime.Value.ToShortDateString() + " " +
                            strReadLogColl[2]);
                    DateTime dtCompEndTime = Convert.ToDateTime
                        (dtEndTime.Value.ToShortDateString() + " " +
                            strReadLogColl[2]);
                    if ((dtCompStartTime >= dtStartTime.Value) && 
                        (dtCompEndTime <= dtEndTime.Value))
                    {
                        boolFlag = true;
                    }
                }
            }
            if ((chkDeleted.Checked == true) && (strReadLogColl[0] == "Deleted"))
            {
                matchRegEx = Regex.Match(strReadLogColl[1], 
                txtPath.Text, RegexOptions.IgnoreCase);
                if (matchRegEx.Success)
                {
                    DateTime dtCompStartTime = Convert.ToDateTime
                    (dtStartTime.Value.ToShortDateString() + " " +
                    strReadLogColl[2]);
                    DateTime dtCompEndTime = Convert.ToDateTime
                    (dtEndTime.Value.ToShortDateString() + " " +
                    strReadLogColl[2]);
                    if ((dtCompStartTime >= dtStartTime.Value) && 
                    (dtCompEndTime <= dtEndTime.Value))
                    {
                        boolFlag = true;
                    }
                }
            }
            if ((chkRenamed.Checked == true) && (strReadLogColl[0] == "Renamed"))
            {
                matchRegEx = Regex.Match(strReadLogColl[1], txtPath.Text, 
                    RegexOptions.IgnoreCase);
                if (matchRegEx.Success)
                {
                    DateTime dtCompStartTime = Convert.ToDateTime
                    (dtStartTime.Value.ToShortDateString() + " " +
                    strReadLogColl[2]);
                    DateTime dtCompEndTime = Convert.ToDateTime
                    (dtEndTime.Value.ToShortDateString() + " " +
                    strReadLogColl[2]);
                    if ((dtCompStartTime >= dtStartTime.Value) && 
                    (dtCompEndTime <= dtEndTime.Value))
                    {
                        boolFlag = true;
                    }
                }
            }
            if ((chkChanged.Checked == true) && (strReadLogColl[0] == "Changed"))
            {
                matchRegEx = Regex.Match(strReadLogColl[1], 
                    txtPath.Text, RegexOptions.IgnoreCase);
                if (matchRegEx.Success)
                {
                    DateTime dtCompStartTime = Convert.ToDateTime
                    (dtStartTime.Value.ToShortDateString() + " " +
                    strReadLogColl[2]);
                    DateTime dtCompEndTime = Convert.ToDateTime
                    (dtEndTime.Value.ToShortDateString() + " " +
                    strReadLogColl[2]);
                    if ((dtCompStartTime >= dtStartTime.Value) && 
                    (dtCompEndTime <= dtEndTime.Value))
                    {
                        boolFlag = true;
                    }
                }
            }
            lvItem = new ListViewItem(strReadLogColl[0]);
            lvItem.SubItems.Add(strReadLogColl[1]);
            lvItem.SubItems.Add(strReadLogColl[2]);
            if (strReadLogColl[0] == "Created")
            {
                lvItem.ForeColor = Color.Blue;
            }
            else if (strReadLogColl[0] == "Changed")
            {
                lvItem.ForeColor = Color.Brown;
            }
            else if (strReadLogColl[0] == "Deleted")
            {
                lvItem.ForeColor = Color.Red;
            }
            else if (strReadLogColl[0] == "Renamed")
            {
                lvItem.ForeColor = Color.Green;
            }
            if (boolFlag == true)
            {
                listViewLog.Items.Add(lvItem);
            }
        }
        tr.Close();
        File.Delete(txtLogPath.Text.Replace("TrackFileActivities.log", "") + 
            "Copy of TrackFileActivities.log");
        timer.Enabled = true;
        if (listViewLog.Items.Count > 0)
        {
            listViewLog.EnsureVisible(listViewLog.Items.Count - 1);
            listViewLog.Items[listViewLog.Items.Count - 1].Selected = true;
        }
    }
    catch (Exception ee)
    {
        MessageBox.Show(ee.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

关注点

需要注意的一件事是,除非您设置,否则您无法更改通知筛选器

fileSystemWatcher.EnableRaisingEvents = false;

如果有人认为如果用户想要为第二个实例打开 Track File Activities Log 窗口,那么他/她可以通过发送

SendMessage(hwdMyForm, 0x0112, 0xF060, 0);

这将处置第一个窗口并为第二个实例打开一个新窗口。

祝您好运,祝您有个愉快的一天!

历史

  • 2008 年 7 月 24 日:初始帖子
  • 2013 年 2 月 13 日:上传代码和已损坏的可执行文件

这是第一个版本。 如果我能够为现有版本添加更多功能和增强功能,我将非常高兴。

© . All rights reserved.