Monitor folder in VB.NET

zhaozj2021-02-17  68

Monitoring folders in VB.NET MONTAQUE

Summary :

Sometimes, in business needs, we have to make changes in monitoring files, such as the creation, deletion, renaming, etc. of the file; and some people must ensure that the important file is read-only, and the change of the file version of the file file . Or, you want to monitor your folder by others, you can delete it, don't know who is dry, when do you do it? So you consider writing a monitoring program, "secret" record folder is operated.

Some people take a regular way, write a desktop application, which may be hidden. Read file information every other event clip and write it to a log file. Then set the system-started event automatic loader, (it seems that many people steal QQ password: (). Its shortcomings: 1, not continuous acquisition information, because they use Timer Tick Events; 2, in the NT system It may be necessary to run, such as administrator identity. There is also a process display in the system, obviously easy Shutdown.

We recommend the program: using the .NET's Windows Service. First, you can overcome the above disadvantages, and more than VB6 is programmed, and WINDOWS SERVICE is written as a palm.

Idea:

Call the System.IO.FileSystemWatcher object in .NET, each time the file or folder changes, call the IO system FileStream and streamWrit to write the change information into the log file.

text:

Windows service about .NET:

Windows services are some long-term running programs, do not need to rely on logging in to users or client programs to keep it. They do not have their own user interface, which can be run in their own unique security level and session context. We are more familiar with the Windows service example contains from the printing pool to the SQL server and its distributed transaction collaboration (DTC). Services can only be run in NT, 2000, and subsequent products, such as XP, which provides a specialized management interface through Microsoft Management Console (MMC) (start -> Run -> Services.msc).

When you create a project in .NET, there is a template for a Windows service, select New. This operation automatically creates a new class for me, which inherited the system.serviceProcess.ServiceBase class built inherited .NET. It also provides me a visual designer, a graphical rapid development tool, which specializes in projects that do not have user interfaces themselves. I can click on this designer and set the name of my service (I named "File Watching").

When a service is activated, the system will locate the corresponding executable, and run the onStart method of the service (which is included in the executable). However, running services are not the same as running executables. The executable is loaded with only the service. The service is accessed through "Service Control Manager" (for example, start and stop).

When "start" is called first on the service, the executable file will call the constructor of the serviceBase to derive class. The onStart command processing method will be called immediately after the constructor is executed. After the service is loaded for the first time, the constructor will not be executed again, so it is necessary to separate the processing executed by the constructor and the processing executed by ONSTART. Any resource that can be released by ONSTOP should be created in onstart. If the service is started again after the service is released, then the creation of resources in the constructor will hinder the correct creation of these resources. "Service Control Manager" (SCM) provides ways to interact with the service. You can pass the "Start", "Start", "Start", "Start", "Continue", or a custom command to the service using the SCM, or a CONTINUE or custom command. SCM uses the value of canstop and canpauseAndContinue, determines whether the service accepts "stop", "pause" or "Continue" command. "Stop", "Pause" or "Continue" will be enabled in the context menu of the SCM when the corresponding attribute canstop or canpauseandContinue is True. If enabled, the corresponding command will be passed to the service and call onstop, onpause, or onContinue. If CANSTOP, CanshutDown, or CanpauseAndContinue is false, even if the corresponding command processing method (such as onstop) has been implemented, it will not be processed.

The above is to create any service, we all involve it, when we use the FileSystemWatcher when monitoring the folder changes, we use FileSystemWatcher.

About FileSystemWatcher:

Listening to file system changes notification, and trigger events when changing files in the directory or directory.

Use the FileSystemWatcher to monitor changes in the specified directory. You can monitor changes in files or subdirectories in the specified directory. This component monitors files on a local computer, a network drive or a remote computer. (Of course, only read-only media media, such as CD and DVD, the properties of their files will 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 the file name. For example, if you want to monitor changes in file mydoc.txt, set the Filter property to "MyDoc.txt". You can also monitor changes in a specific type file. For example, if you want to monitor changes in a text file, set the Filter property to "* .txt".

Monitors several changes in the directory or file. For example, you can monitor the Attributes, LastWrite dates, and time or size of files or directories. This is achieved by setting the FileSystemWatcher.NotifyFilter property to the NotifyFilters value.

Renamble, delete, or creation of files or directories can be monitored. For example, if you want to monitor the renaming of a text file, set the filter attribute to "* .txt", and call one of the WaitForChanged methods, give the WatcherChangeTypes value.

Demo:

Create a new project, select the Windows service type, named WinServiceFileWatching, we see the System.ServiceProcess name space in Project's reference (this is the function set of created a service). Select FileSystemWatcher1 from the components in the tool, drag and drop to Service1's design mode, and then set the following properties: Filter Get or set the filter string to determine which files are monitored in the directory. We set to *. *, All files

INCLUDESUBDIRECTORIES Gets or sets a value indicating whether the subdirectory in the specified path is monitored. Set to True

PATH Gets or Sets the path to the directory you want to monitor to monitor the object we have to monitor, such as C: / DonnetData

Then add the following code:

Protected Overrides Sub onstart (Byval Args () AS String

'Add the code that starts the service here. This method should set specific operations

'So that the service can perform its work.

FILESYSTEMWATCHER1.EnableraisingEvents = TRUE

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

'FileSystemWatcher1.path = args (0)

End Sub

'Creating a file (clip) Trigger, record creation information to e: /log.txt

Private sub filesystemwatcher1_created (byval e as system.io.filesystemEventArgs) handles FileSystemWatcher1.created

DIM FS AS NEW FISTREAM ("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

The 'Rename file (clip) is triggered, recorded creation information to E: /LOG.TXT

Private sub filesystemwatcher1_renamed (byval e AS object, byval e as system.io.renamedendeventargs) Handles FileSystemWatcher1.Renamed

DIM FS AS NEW FISTREAM ("E: /Log.txt", FileMode.Append)

DIM SW AS New StreamWriter (fs)

Sw.writeline (now () & Microsoft.visualBasic.vbtab & "Rename" & E.OLDFULLPATH & "-" & E.FullPath)

SW.CLOSE ()

fs.close ()

End Sub

'Remove the file (clip) Trigger, record the creation information to e: /log.txt

Private Sub FileSystemWatcher1_Deleted (ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.DeletedDim 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 is already written, following a installer:

To click Right click on the Service's design mode, select Add the installer. The system will automatically add a class ProjectInstaller, and there is a ServiceProcessInstaller1 and ServiceInstaller1 on the design mode. Set the Display Name of ServiceInstaller1 for File Watching Service, StartType is Automatic, which is automatically started. Set the Account of ServiceProcessInstaller1 to Localsystem.

Since the service cannot be run, we choose to generate a solution. OK!

Finally install our service:

.NET Framework comes with a tool, installutil, using very simple installutil c: /winservicefilewatching/bin/winservicefileWatch ,.exe 'path that just compiled good programs

This is installed, Uninstall is also easy. First SCM is closed, installutil / u c: /.../ WinServiceFileWatching.exe 'The Same Path

This will make more services in the system's Services, displayed as File Watching Service, and select Start to start monitoring ...

to sum up:

Call the System.IO.FileSystemWatcher object in .NET, each time the file or folder changes, call the IO system FileStream and streamWrit to write the change information into the log file. In fact, the .NET powerful built-in integration function is used to simply speak the complex file.

转载请注明原文地址:https://www.9cbs.com/read-30874.html

New Post(0)