Urgen
Urgen

Reputation: 1223

Windows Temp File Delete Service

I have created a Windows Service to delete local temp files/folders and it's run but does not delete files and folders:-

class Program
{
    static void Main(string[] args)
    {
        var exitCode = HostFactory.Run(e =>
        {
            e.Service<DeleteTempFileService>(x =>
            {
                x.ConstructUsing(() => new DeleteTempFileService());
                x.WhenStarted(execute => execute.Start());
                x.WhenStopped(execute => execute.Stop());
            });
            e.SetServiceName("DeleteTempFileService");
            e.SetDisplayName("Delete Temp File Service ");
        });
    }
}

public class DeleteTempFileService
{
    public FileSystemWatcher _fileWatcher;       

    public bool Start()
    {
        _fileWatcher = new FileSystemWatcher(@"C:\Users\xyz\AppData\Local\Temp", "*.*");
                _fileWatcher.Deleted += TempDeletionService;
                _fileWatcher.EnableRaisingEvents = true;
                _fileWatcher.IncludeSubdirectories = true;
                return true;
    }

    private void TempDeletionService(object sender, FileSystemEventArgs watcherService)
    {               
        var dir = new DirectoryInfo(watcherService.FullPath);
        foreach(var file in Directory.GetFiles(dir.ToString()))
        {
            File.Delete(file);
        }
    }

    public bool Stop()
    {
        _fileWatcher.Dispose();
        return true;
    }
}

Program runs fine but it does not delete the files/folders in local temp directory. I have tried different approaches but no help.

Upvotes: 0

Views: 1440

Answers (2)

Lance U. Matthews
Lance U. Matthews

Reputation: 16606

Firstly, your code will never delete directories because Directory.GetFiles only returns files, not directories. To retrieve both files and directories, call Directory.GetFileSystemEntries. Whichever method you call, the overload that takes a single path parameter only returns objects that are immediate children of the specified directory. If you want to include objects in descendent directories, you need to call an overload that takes a SearchOption parameter.

Secondly, what your DeleteTempFileService class is doing is creating a FileSystemWatcher to raise an event when a temp file is deleted, at which point it deletes all immediate child files of the temp directory. You are waiting on the deletion of at least one temp file to trigger (via the Deleted event) the deletion of all temp files.

You can make this more predictable and less complicated. If you want to delete files from the temp directory, then just delete files from the temp directory. You already have the code to do this in your TempDeletionService method:

var dir = new DirectoryInfo(@"C:\Users\xyz\AppData\Local\Temp");
foreach(var file in Directory.GetFiles(dir.ToString()))
{
    File.Delete(file);
}

Just run that. Unless you want your service to be deleting temp files as they are created or modified (which seems problematic; applications need those files at least initially), you don't need a FileSystemWatcherhere.

Upvotes: 1

win10shit
win10shit

Reputation: 1

I don't know if I really understand your purpose. It seems that you just want to delete the temporary files automatically. If this is the case, your approach seems to have some problems: You may have misunderstood FileSystemWatcher? FileSystemWatcher is triggered after the file operation, you registered the monitoring of the file deletion operation, but after the file is deleted, what is the use? You can monitor the FileSystemWatcher.Created operation and then delete the corresponding file/folder. If you just want to delete the file, I think it is a good choice to use Timer or Thread timing. After all, the overhead of FileSystemWatcher is a bit big, unless you need real-time operation.

Say a little off topic: I suggest not to use the anonymous method and other syntactic sugars, write traditional methods, anonymous methods can make people lazy, there is almost no benefit: not conducive to packaging and isolation, not conducive to reading, affecting code Structure and robustness. Don't use the var keyword, except that it can be lazy, it doesn't help. A little sugar will be good, too much sugar will make people sick, now Microsoft and C# have become more and more weird, C# has become "complex", the grammar is complicated, it becomes more and more weird, if it is completely used The latest syntactic sugar and traditional grammar to write, not even the same language, is this the succinct C#? Of course, the rhythm of syntactic sugar is also rampant in other languages, which is not a good phenomenon.

Finally, thanks to Google Translate, my English dictation level is worse than my English reading level.

Upvotes: 0

Related Questions