.net MVC前后端通信—SingleR,文件监控FileSystemWatcher

在这里介绍一个通过文件监视FileSystemWatcher和SingleR实现对文件的监控提示。

1、首先利用Nuget安装SingleR;

2、安装完SingleR之后,在项目中会多出来SingleR的dll文件和两个JS文件;

3、修改Startup类,(若项目中没有Startup类,通过搜索Startup添加);

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }

4、添加chatHub类:

    public class ChatHub : Hub
    {
        private string filePath = AppDomain.CurrentDomain.BaseDirectory;

        /// 
        /// 发送信息给所有用户
        /// 
        /// 
        public void Hello(string message)
        {
            Clients.All.hello(message);
        }

        public void watcherTxt()
        {
            WatcherStrat(filePath, "file.txt");
        }

        private void WatcherStrat(string path, string filter)		//监控文件
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = path;
            watcher.Filter = filter;
            watcher.Changed += new FileSystemEventHandler(OnProcess);
            watcher.Created += new FileSystemEventHandler(OnProcess);
            watcher.Deleted += new FileSystemEventHandler(OnProcess);
            watcher.Renamed += new RenamedEventHandler(OnRenamed);
            watcher.EnableRaisingEvents = true;
            watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess
                                   | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;
            watcher.IncludeSubdirectories = true;
        }

        public void OnProcess(object source, FileSystemEventArgs e)
        {
            if (e.ChangeType == WatcherChangeTypes.Created)
            {                
                Clients.All.hello("Created");
            }
            else if (e.ChangeType == WatcherChangeTypes.Changed)
            {
                Clients.All.hello("Changed"); 
            }
            else if (e.ChangeType == WatcherChangeTypes.Deleted)
            {
		Clients.All.hello("Deleted"); 
 	} } 
	private void OnRenamed(object source, RenamedEventArgs e) {
		Clients.All.hello("Renamed"); 
 	}
	}


5、修改view页面,实现前后交互:


      
            $(function () {
                //创建一个hub服务
                var hub = $.connection.chatHub;
                $.connection.hub.start()
                    .done(function () {
                        hub.server.watcherTxt();	//进入后台方法
                    })
                    .fail(function () {
                        alert("连接失败!");
                    });
                hub.client.hello = function (name) {	//前台hello方法
                    alert(name);
                };
                $("#sayHello").click(function () {
                    hub.server.hello("Jack");		//向后台发送数据
                })
            });

 

你可能感兴趣的:(.net,MVC)