Spot The Bug 1: Pocket PC


(Doh! I had a mistake in the code…. Fixed it now. Was supposed to be !Directory.Exists) 


The following code executes at the beginning of a Pocket PC application run. It makes sure that the settings folder exists for that application.



using System;


using System.Collections.Generic;


using System.Text;


using System.IO;


 


namespace ConsoleApplication6


{


       class Program


       {


              static void Main(string[] args)


              {


                     if (!Directory.Exists(Config.SettingsDirectory))


                     {


                           Directory.CreateDirectory(Config.SettingsDirectory);


                     }


              }


       }


}


 


Things to ignore: Process race conditions, file system lock issues.

Comments (8)

  1. Dave Crawford says:

    Well, seems that it would throw an exception when the Directory.CreateDirectory call is made, in that the it is  called only if the directory for the settings already exists.

    The "correct" version might be something like this:

    if (!Directory.Exists(Config.SettingsDirectory))

                        {

                              Directory.CreateDirectory(Config.SettingsDirectory);

                        }

    DC

  2. DarronJ says:

    Is it really this simple? Is this creating a directory "if" it exists, rather than if it does not?

  3. Darron says:

    All potential outcomes are bad for this code. If the directory exists, the code would try to create it again and get an exception. If the directory did not exist, the program would continue to run without having it’s settings directory.

    A healthy dose of test driven development woud stop this type of error dead in its tracks.

  4. MSDNArchive says:

    1) you don’t get an exception if the dir already exists – that’s one of the reasons why this bug can be hard to catch, since if the dir already exists, the code works fine.

    2) this is a good reason to just call Directory.CreateDirectory and not bother with the if check, since there’s a chance of screwing up said if check.  This is one of the reasons it doesn’t throw if the dir already exists, so you can do exactly that.

  5. Shahar says:

    My mistake. 🙂

    The bug you guys saw is a bug in the example, not the real question.

    I fixed it now. It’s !Directory.Exists().

    Apologies.

  6. JamesCurran says:

    Well, as jmanning points out, it should be just

    static void Main(string[] args)

    {

            Directory.CreateDirectory(Config.SettingsDirectory);

    }

    Otherwise, what do we know about Config.SettingsDirectory?  (Google reports that this is the only page on the internet that contains "Config.SettingsDirectory")

  7. Shahar says:

    Config.SettingsDirectory just returns where the folder containing the settings for the application is located at.

  8. LuisBE says:

    Escaping the backslahes in Config.SettingsDirectory?