Use FileSystemWatcher in ASP.net

2019-09-20 07:34发布

问题:

I have created File system watcher for console application. it is working flawless.

unliess you press 'q' its keep listning the folder for adding files and display name of the files when found.

public void FileWatcher()
        {
            while (true)
            {

                FileSystemWatcher watcher = new FileSystemWatcher();
                watcher.Path = @"C:\\WATCH-FOLDER";
                watcher.IncludeSubdirectories = true;

                watcher.NotifyFilter = NotifyFilters.Attributes |
                NotifyFilters.CreationTime |
                NotifyFilters.DirectoryName |
                NotifyFilters.FileName |
                NotifyFilters.LastAccess |
                NotifyFilters.LastWrite |
                NotifyFilters.Security |
                NotifyFilters.Size;

                watcher.Filter = "*.*";

                watcher.Changed += new FileSystemEventHandler(OnChanged);
                watcher.Created += new FileSystemEventHandler(OnChanged);

                watcher.EnableRaisingEvents = true;
            }

        }

        public void OnChanged(object source, FileSystemEventArgs e)
        {
            Console.WriteLine("{0}, with path {1} has been {2}", e.Name, e.FullPath, e.ChangeType);
        }

        public void OnRenamed(object source, RenamedEventArgs e)
        {

            Console.WriteLine(" {0} renamed to {1}", e.OldFullPath, e.FullPath);
        }

but now how can i use this in my web application. what i want, when ever file adds in folder it picked and and insert info in database. so when i press show all so this info would be part of existing data in table.

But i have no idea where to put function. Some people says put it in Global.asax file, and some says put in main page, or add thread. I am completly confused and have no idea how to do that.

回答1:

Why don't you host this file watcher in app_start in global.asap, so even if iis shut down your app after 20min of inactivity, then it will relaunch a new watcher whenever a user hit your application again.

This is a valid solution, and can be the only solution for those who don't own the server, i. e. Who host their web on shared hosting and have no access to Windows services



回答2:

This process should be placed in a windows service application. You should not attempt to host it within an asp.net application.

If you are using visual studio, then you have the ability to make Windows Services. File -> New - Project -> C# -> Window Service. The code that you have in your test console app would go in the OnStart event of a class derived from ServiceBase.



回答3:

Probably a bit late but putting aside what's right and wrong from an architectural ethics point of view this solves the problem ...

Scott Hanselman had this to say:

http://www.hanselman.com/blog/HowToRunBackgroundTasksInASPNET.aspx

... he offers up his own ideas and also refers to this ...

http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx/

... the article talks about using this ...

https://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.registerobject.aspx

... to basically have something that behaves like a task manager / windows process embedded within the IIs worker process, which allows us to do something like this in the app ...

using System;
using System.Threading;
using WebBackgrounder;

[assembly: WebActivator.PreApplicationStartMethod(
  typeof(SampleAspNetTimer), "Start")]

public static class SampleAspNetTimer
{
    private static readonly Timer _timer = new Timer(OnTimerElapsed);
    private static readonly JobHost _jobHost = new JobHost();

    public static void Start()
    {
        _timer.Change(TimeSpan.Zero, TimeSpan.FromMilliseconds(1000));
    }

    private static void OnTimerElapsed(object sender)
    {
        _jobHost.DoWork(() => { /* What is it that you do around here */ });
    }
}