tags:

views:

295

answers:

4

Hi all,

Why would the code below throw a io.system.directorynotfound exception? I can't recreate the problem myself but another user of my code does see it, any ideas why? Thanks

try
{
  //create path
  string strAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\MyApp\\Data\\logs";
  //check path exists
  if (!System.IO.File.Exists(strAppData))
  {
      System.IO.Directory.CreateDirectory(strAppData);
  }
  System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(strAppData);
  int count = dir.GetFiles().Length;

  if (count > 100)
  {
      string[] files = System.IO.Directory.GetFiles(strAppData);

      foreach (string file in files)
      {
          System.IO.File.Delete(file);
      }
  }


  this.fileName = fileName;
  // delete the file if it exists
  if (File.Exists(fileName))
  {
      //delete the file
      File.Delete(fileName);
  }

      // write the data to the file
      fs = File.OpenWrite(fileName);
      sWriter = new StreamWriter(fs);

      sWriter.WriteLine(headerText);

      sWriter.Flush();
      sWriter.Close();
}
catch (Exception exp)
{
    throw new Exception(exp.Message);
}
+3  A: 

Have you tried using System.IO.Directory.Exists rather than System.IO.File.Exists when checking to see if the path exists?

Dustin Campbell
+1  A: 

You're checking for the existence of a directory using System.IO.File rather than System.IO.Directory. It probably works on your machine because that directory already exists, and so the check doesn't matter.

Either way, you need to remember that the file system is volatile. Rather than checking existence, try to open the resource and handle the exception when it fails.

Joel Coehoorn
+1  A: 

Check that the directory exists, not the file...

Although you're checking it, and creating it if it doesn't exist. You don't know if they have privelages to create the directory. So your Directory.CreateDirectory call may well be failing too and then sub-sequently the rest of the code will fail

Ian
+1  A: 

http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx

"Remarks

The Exists method should not be used for path validation, this method merely checks if the file specified in path exists. Passing an invalid path to Existsl returns false. "

That is your error right there. Your validation does not ensure that the path to the file exists

Sergio