在ASP.NET中使用FileSystemWatcher来监控文件目录
在ASP.NET中我们有时会访问文件,但我们如果不想让代码每次都重新读取文件内容的话,我们可以使用FileSystemWatcher,这在有些情况是是很不错的选择,以下代码演示如何在ASP.NET中使用FileSystemWatcher来监控文件目录,以及在这种监控方式下IIS如何管理Appdomain以及Thread。
首先,我们利用Application_Start事件来在整个Application中创建唯一的FileSystemWatcher实例,并设置关联的监听方法,在监听方法中我们重新读取文件夹信息,并保存在Application变量中。
Global.asax
<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Threading" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
if (Application["FileSystemWatcher"] == null)
{
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher("E:\\Temp", "*.*");
Application["FileSystemWatcher"] = fileSystemWatcher;
fileSystemWatcher.NotifyFilter = NotifyFilters.FileName|NotifyFilters.LastWrite|NotifyFilters.CreationTime;
fileSystemWatcher.Created += fileSystemWatcher_Changed;
fileSystemWatcher.Changed += fileSystemWatcher_Changed;
fileSystemWatcher.Deleted += fileSystemWatcher_Changed;
fileSystemWatcher.Renamed += fileSystemWatcher_Changed;
fileSystemWatcher.EnableRaisingEvents = true;
}
}
void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
System.Diagnostics.Debug.WriteLine(string.Format("{0}, D:{1}, T:{2} E:fileSystemWatcher_Changed", DateTime.Now, AppDomain.CurrentDomain.Id, Thread.CurrentThread.ManagedThreadId));
if (Application["EventList"] == null)
{
Application["EventList"] = new List<String>();
}
List<String> eventList = (List<String>)Application["EventList"];
eventList.Add(string.Format("{0}, D:{1}, T:{2} E:fileSystemWatcher_Changed", DateTime.Now, AppDomain.CurrentDomain.Id, Thread.CurrentThread.ManagedThreadId));
Application["FileList"] = Directory.GetFiles("E:\\Temp", "*.*");
}
</script>
其次,我们创建一个页面来显示保存在Application变量中的文件夹等的信息,以验证FileSystemWatcher是否起效。
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="File list:"></asp:Label>
</div>
<asp:ListBox ID="lstFile" runat="server" Width="583px">
</asp:ListBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Event list:"></asp:Label>
<br />
<asp:ListBox ID="lstEvent" runat="server" Width="579px">
</asp:ListBox>
</form>
</body>
</html>
Default.aspx.cs
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lstFile.DataSource = Application["FileList"];
lstFile.DataBind();
lstEvent.DataSource = Application["EventList"];
lstEvent.DataBind();
}
}