Web applications often involve reading from and writing to files local to the web application server. In the case of reading from a file, errors may occur if the proper checks are not in place. One popular way of insuring errors don’t occur during runtime is to check if a file exists before attempting to read the file.

if (File.Exists(”C:\\testfile.txt”))
{
return true;
}
else
{
return false;
}

This method utilizes the Exists function, part of the File class, to check if a file can be found at the specified directory. The string must be reachable from the server on which the web application resides. When expressing the input string, be sure to properly format your directory and file with double back slashes. To use File.Exists, be sure to include the following at the top of your file.

using System.IO;

This entry was posted on Wednesday, April 2nd, 2008 at 6:38 pm and is filed under C#. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

One Response

  1. dug says

    return File.Exists(”C:\\testfile.txt”);

Leave a Reply