Vb. Change of monitoring folders in net

Source: Internet
Author: User
Tags constructor continue file system log resource

Summary:

Sometimes, in the business needs, we constantly monitor the changes in files, such as file creation, deletion, renaming and so on, and some people want to ensure that important files are read-only, and to report the changes in the file version in a timely manner. Or, do you want to monitor your folders to be changed by others and arbitrarily deleted without knowing who did it and when? So you're thinking about writing a watchdog that says "sneak" records of how folders are being manipulated.

Some people take the conventional approach of writing a desktop application, whose interface may be hidden. Use every other event fragment to read the file information, and then write to a log file. Then set up the system-initiated event loader, (as if a lot of people are stealing QQ passwords like this: (). Its disadvantage: 1, not continuous access to information, because they used the timer tick event; 2, in the NT system, may have to certain permissions to run, such as Administrator identity. There are also processes in the system that are clearly easy to shutdown.

Our proposed scheme: adoption. NET Windows Service. First of all, you can overcome the above disadvantages, and more VB6 programming,. NET writes Windows service as the reverse palm.

Ideas:

Call the System.IO.FileSystemWatcher object in a service created by. NET, and each time the file or folder being monitored changes, the FileStream and StreamWriter of the IO system are invoked to write the change information to the log file.

Body:

About. NET in Windows services:

Windows services, which are long-running programs, do not need to rely on logged-in users or client programs to keep it running. They have no user interface of their own and can run in their own unique security level and session context. The Windows service paradigm that we are familiar with includes a print pool to a SQL Server and its Distributed transaction Collaboration (DTC). Services can run only with NT, 2000, and successor products such as XP, and they provide a dedicated management interface (starting-> run->services.msc) through Microsoft Management Console (MMC).

When you create a project in. NET, you have a template for the Windows service, and you choose New. This operation automatically creates a new class for me, which is inherited. NET built the System.ServiceProcess.ServiceBase class. At the same time it provides me with a visual designer, a graphical tool for rapid development, especially for projects that do not have a user interface of their own. I can click on this designer to set the name of my service (I'm named "File watching").

When a service is started, the system locates the appropriate executable file and runs the OnStart method of the service, which is contained within the executable file. However, running the service is not the same as running the executable file. The executable file loads only the service. Services are accessed through the Service Control Manager (for example, start and stop).

When you first invoke start on a service, the executable file invokes the constructor of the ServiceBase derived class. The OnStart command processing method is called immediately after the constructor executes. After the service is first loaded, the constructor is not executed again, so it is necessary to separate the processing performed by the constructor from the processing performed by the OnStart. Any resources that can be freed by OnStop should be created in OnStart. If the service starts again after OnStop frees resources, creating a resource in the constructor prevents the resource from being created correctly.

The Service Control Manager (SCM) provides a way to interact with a service. You can use SCM to pass the start (start), Stop (stop), pause (Pause), continue (Continue), or custom command to a service. The SCM uses the values of CanStop and canpauseandcontinue to determine whether the service accepts the stop, pause, or Continue command. Stop, pause, or Continue is enabled only in the context menu of the SCM if the corresponding property canstop or CanPauseAndContinue in the service class is true. If enabled, the corresponding command is passed to the service and the OnStop, OnPause, or oncontinue are invoked. If CanStop, CanShutdown, or canpauseandcontinue is false, it is not processed even if the corresponding command processing method, such as OnStop, is implemented.

The above is to create any one of the services we will be involved in, but specifically in the Monitoring folder changes, we use the FileSystemWatcher.

About FileSystemWatcher:

Listens for file system change notifications and raises events when a file in the directory or directory changes.

Use FileSystemWatcher to monitor changes in the specified directory. You can monitor changes to files or subdirectories in the specified directory. This component can monitor files on a local computer, a network drive, or a remote computer. (Of course, read-only media media such as CDs and DVDs, the properties of their files do not change, so they cannot trigger events)

To monitor changes in all files, set the Filter property to an empty string (""). To monitor a specific file, set the Filter property to that file name. For example, to monitor changes in the file MyDoc.txt, set the Filter property to "MyDoc.txt." You can also monitor changes in a particular type of file. For example, to monitor changes in a text file, set the Filter property to "*.txt."

You can monitor a number of changes in a directory or file. For example, you can monitor changes in the Attributes, Lastwrite date and time, or Size of a file or directory. This is accomplished by setting the Filesystemwatcher.notifyfilter property to one of the notifyfilters values.

You can monitor the renaming, deletion, or creation of files or directories. For example, to monitor the renaming of a text file, set the Filter property to "*.txt" and call one of the waitforchanged methods, giving the renamed of the WatcherChangeTypes value when invoked.

Demo:

Create a new project, select the Windows service type, name Winservicefilewatching, We saw that the System.ServiceProcess namespace was automatically added to project references (this is the set of functions that created a service). Select FileSystemWatcher1 from the components in the tool, drag and drop to the design mode of Service1, and set the following properties:

Filter Gets or sets the filter string that determines which files are monitored in the directory. We set it to *.*, that is, all files

IncludeSubdirectories Gets or sets a value that indicates whether to monitor subdirectories in the specified path. Set to True

Path Gets or sets the path set for the directory to monitor for the objects we want to monitor, such as C:\DonnetData

Then add the following code:

Protected Overrides Sub OnStart (ByVal args () as String)

' Add code to start the service here. This method should set the specific action

' So that the service can perform its work.

Filesystemwatcher1.enableraisingevents = True

' We can also dynamically set the objects to be monitored based on the input parameters args

' Filesystemwatcher1.path= args (0)

End Sub

' Create a file (folder) when the trigger, record creation information into the E:\log.txt

Private Sub filesystemwatcher1_created (ByVal sender as Object, ByVal e as System.IO.FileSystemEventArgs) Handles Filesyst emwatcher1.created

Dim FS as New FileStream ("E:\log.txt", Filemode.append)

Dim SW as New StreamWriter (FS)

Sw. WriteLine (Now () & Microsoft.VisualBasic.vbTab & "Create" & E.fullpath)

Sw. Close ()

Fs. Close ()

End Sub

' Rename file (folder) when triggered, record creation information to E:\log.txt

Private Sub filesystemwatcher1_renamed (ByVal sender as Object, ByVal e as System.IO.RenamedEventArgs) Handles FILESYSTEMW Atcher1. Renamed

Dim FS as New FileStream ("E:\log.txt", Filemode.append)

Dim SW as New StreamWriter (FS)

Sw. WriteLine (Now () & Microsoft.VisualBasic.vbTab & "renaming" & E.oldfullpath & "-" & E.fullpath)

Sw. Close ()

Fs. Close ()

End Sub

' Delete file (folder) when trigger, record create information to E:\log.txt

Private Sub filesystemwatcher1_deleted (ByVal sender as Object, ByVal e as System.IO.FileSystemEventArgs) Handles Filesyst emwatcher1.deleted

Dim FS as New FileStream ("E:\log.txt", Filemode.append)

Dim SW as New StreamWriter (FS)

Sw. WriteLine (Now () & Microsoft.VisualBasic.vbTab & "Delete" & E.fullpath)

Sw. Close ()

Fs. Close ()

End Sub

So far, this service has been written, the following is a Setup program:

        in the service design mode right-click, select Add Installer. The system automatically adds a class ProjectInstaller with a ServiceProcessInstaller1 and ServiceInstaller1 on the design pattern. Setting ServiceInstaller1 display name to Automatic for file watching Service,starttype indicates automatic startup. Set the ServiceProcessInstaller1 account to LocalSystem.

Because the service is not operational, we choose to build the solution. Ok!

Finally installs our service:

The        .net Framework brings a tool, InstallUtil, Use a very simple installutil c:\winservicefilewatching\bin\winservicefilewatching.exe ' just the path of the compiled program

         This will be installed, uninstall is also very easy. First off the service in the SCM, installutil/u C:\...\winservicefilewatching.exe ' the same path

provides a service in the system's services that appears as file Watching Service, select start to start monitoring ...

        Summary:

        in. NET creates a service in which the System.IO.FileSystemWatcher object is invoked, each time the file or folder being monitored changes, the FileStream and StreamWriter of the IO system are invoked to write the change information to the log file. Actually took advantage of. NET powerful built-in integration features to put complex files in simple words.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.