Click here to Skip to main content
15,885,278 members
Articles / Programming Languages / C#
Tip/Trick

How to write a basic file logging application

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
6 Jul 2013CPOL4 min read 10.1K   11   2
Logging the most important directories!

Introduction

Well, basically, I've been trying to find a decent article that displays how to log files and folders but all of them tend to go on only one folder. So, for this article in particular I've shown how to log multiple folders in just a few lines of code.

How would we get started?

Well basically, the first things you would probably want to know is how we log a certain directory. Instead of writing our own complicated way of checking folders I am using the FileSystemWatcher, but as I remembered, when this name popped up I immediately quitted the article. But before you do that, I would like you to continue on reading as some of this might come in handy.

The FileSystemWatcher is a nice class that handles file system watching easily, and threadidly, making it an easy job but for some perhaps a bit difficult. You might want to know exactly how this works, what it does, and so forth. But I am unable to explain all of that to you in this article so If you have any more questions afters this article it might be a good time to visit this page right here.

After you have a basic knowledge about the FileSystemWatcher there is something else you need to know. Since the FileSystemWatcher handles everything in threads in can become a nasty thing to update info to for instance a listbox. We can easily solve this, as I will explain this later in the article.

Writing the file watchers!

Love this part of the articles, as this mainly focusses on the code and does not require a lot of explaining and such. However, I will pin-point some of the points of interests and explain what it does.

So to get started on writing a multiple folder logging application you would want to know how to get multiple folders. This can either be done by focussing on the main folders which are found in Environment.SpecialFolder, or, you could even make your own list of folders by creating an array and looping through that.

Creating the file watchers according to a list;

C#
/* All the directory watchers we currently have. */
public List<FileSystemWatcher> Watchers = new List<FileSystemWatcher>(); 

/// <summary>
/// Creates file watchers for all the important folders.
/// </summary>
public void CreateFileWatchers()
{
    /* Create a list to prevent duplicates. */
    List<String> Paths = new List<String>();

    foreach(System.Environment.SpecialFolder SpecialFolder 
      in Enum.GetValues(typeof(Environment.SpecialFolder)))
    {
        /* Create a string to add to Paths and then check if we do not already have it. */
        string Path = Environment.GetFolderPath(SpecialFolder);

        if (!Paths.Contains(Path))
        {
            /* Add the path. */
            Paths.Add(Path);

            /* Create a file watcher. */
            FileSystemWatcher Watcher = new FileSystemWatcher();
            Watchers.Add(Watcher);

            /* Set the properties of the watcher. */
            Watcher.Path = Path;
            Watcher.Created += new FileSystemEventHandler(Watcher_Created);
            Watcher.Deleted += new FileSystemEventHandler(Watcher_Deleted);
            Watcher.Changed += new FileSystemEventHandler(Watcher_Changed);

            /* Let the watcher watch. */
            Watcher.EnableRaisingEvents = true;
        }
    }
}

So the above code might give you already a quick idea of how it works, if you are still unsure keep on reading otherwise, go and scroll a bit down.

So to get started I've created a basic list to hold all the file watchers. Next I created a special void to create all the file watchers, this is done in a void, because I love to keep everything sorted in my code, and not do four hundred different tasks in the same 'Main' void.

This code creates a list of strings which will hold all the paths, this can be used to make sure we do not check the same path, as this may occur with Environment.SpecialFolder since it has two desktop locations. Next I loop through the whole Environment.SpecialFolder list using Enum.GetValues and continue on from there. From there, I get the path to the 'SpecialFolder' and make sure it is not in our Paths list so that we can create a new watcher that has its original path and not one that already exists.

We then add the path to the list for the next loop to be checked on and create a new File Watcher. The File Watcher will be added to its own list that we created before we even started the void. The watcher then gets its basic properties, such as the path. We then register the events, this can be easily done by pressing tab twice when you're hovering over the event in the little list that pops ups when accessing variables. And last but not least; registering the events.

Handling the threaded events!

Last but not least, how would you go ahead and use the differences found. E,g; Created, deleted, changed. Well, these are all registered in events, but, as I pointed out earlier, these events are threaded meaning that when changing something to the form, for instance a ListBox, you will have to invoke a delagate.

How would you invoke a delagate, it's simple:

C#
void Watcher_Created(object sender, FileSystemEventArgs e)
{
    /* Back the file up if needed. */
    Backup(e.FullPath);
}

/// <summary>
/// Backs up a file.
/// </summary>
/// <param name="Path"></param>
public delegate void BackupDelegate(string Path);
public void Backup(string Path)
{
    if (this.listBox.InvokeRequired)
    {
        this.listBox.Invoke(new BackupDelegate(Backup), Path);
    }
    else
    {
        this.listBox.Items.Add(Path);
    }
} 

Well, this is hopefully explains itself on how to use this on your own control. Perhaps a textbox, if you are still not sure, all you have to do is invoke it on the control, and instead of "ctrl.Items.Add", you could write "ctrl.Text = Path".

Points of Interest

What I have learned is how to access variables from other threads using delegates. I'm still unsure about how delegates work, but I have learned on how to use them by invoking.

Also, as a little P.S, I apologize for my bad grammar. I'm not English and not sure if it's good or not, but I hope it's at least understandable by other forum members and guests.

History

Released the article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralLogging? Pin
waleri8-Jul-13 20:09
waleri8-Jul-13 20:09 
GeneralRe: Logging? Pin
Deviant Sapphire9-Jul-13 15:04
Deviant Sapphire9-Jul-13 15:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.