Vikash Pandey
Vikash Pandey

Reputation: 4295

File watcher in windows service

I am beginner trying to develop a Windows service which keeps checking a folder (or group of folders) for any new file or changed files. As soon as it detects any new file or changes (to files or folders) then it copies the files (and any new folders) and paste it to another location.

I have done the same thing with a Windows Forms application but in a Windows Service I don't know what to do - how can I do this in a Windows Service?

Upvotes: 2

Views: 3779

Answers (4)

theking2
theking2

Reputation: 2842

a System.IO.FileWatcher based solution:

WatchFile/WatchFile.psm1

# Define the file path to monitor
function Watch-File {
    [cmdletbinding()]
    Param (
        [string]
        $Path
    )
    # Create a FileSystemWatcher object
    $fileWatcher = New-Object System.IO.FileSystemWatcher
    $fileWatcher.Path = (Get-Item $Path).DirectoryName
    $fileWatcher.Filter = (Get-Item $Path).Name
    $fileWatcher.IncludeSubdirectories = $false
    $fileWatcher.EnableRaisingEvents = $true

    # Define the event action when a change is detected
    # in this case toast a message
    $action = {
        $file = $Event.SourceEventArgs.FullPath
        $eventType = $Event.SourceEventArgs.ChangeType
        $message = "File '$file' has been $eventType"
        Show-Notification "Watch-File" $message 
    }

    # Register the event handler
    Register-ObjectEvent -InputObject $fileWatcher -EventName "Changed" -SourceIdentifier FileChanged -Action $action

    Write-Host "Monitoring file: $Path. Press Ctrl+C to stop."

    # Keep the script running
    try {
        while ($true) {
            Start-Sleep -Seconds 7
        }
    }
    finally {
        # Unregister the event handler when the script is stopped
        Unregister-Event -SourceIdentifier FileChanged
        $fileWatcher.EnableRaisingEvents = $false
    }
}

Calling with Watch-File C:\error.log will watch for changes in C:\error.log and display a desktop notification.

As System.IO.FileSystemWatcher is a .NET object this will only work in WindowsPowerShell not in powershell-core.

Upvotes: 0

Narendra
Narendra

Reputation: 1412

Here is how we can complete this task using file watcher without timer

public void ProcessFile(string filepath)
    {
        var fileN ="newfilename";
        string destfile = "E:\\2nd folder" + fileN;
        File.Copy(filepath, destfile, true);
    }

    protected override void OnStart(string[] args)
    {
       String[] files = Directory.GetFiles("E:\\", "*.*");
        foreach (string file in files)
        {
            ProcessFile(file);
        }
        var fw = new FileSystemWatcher("folderpath");
        fw.IncludeSubdirectories = false;
        fw.EnableRaisingEvents = true;
        fw.Created += Newfileevent;

    }
    static void Newfileevent(object sender, FileSystemEventArgs e)
    {
        ProcessFile(e.FullPath);

    }

Upvotes: 0

Vikash Pandey
Vikash Pandey

Reputation: 4295

Here is correct answer for this question

public static void MyMethod()
{
    String[] files = Directory.GetFiles("E:\\", "*.*");
    foreach (string file in files)
    {
        var fileN = file.Substring(2);
        string destfile = "E:\\2nd folder" + fileN;
        File.Copy(file, destfile, true);
    }
}

polling is needed to watch the file after a fix interval of time....this code is watch the file 2sec

protected override void OnStart(string[] args)
{
    timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
    timer.Interval = 2000;
    timer.Enabled = true; 
    MyMethod();
}

Upvotes: -4

Darin Dimitrov
Darin Dimitrov

Reputation: 1039328

You could use the FileSystemWatcher class.

Upvotes: 7

Related Questions