Website Design United States, Website Design California, Website Designing United States, Website Designing California

Quick way to see if a file or folder exists using C Sharp - C#

Eric D. Burdo

http://thenxtstep.blogspot.com/

Two functions that will allow you to easily check if a file or directory (folder) exist. Simply pass the path of the file or directory to the appropriate function and it will return true if it exists or false otherwise.

 

using System;

class MainClass
{
public static void Main(string[] args) {
string sFile = "C:\\abcd.txt"; //Assign a file, be sure to escape the \
string sDir = "c:\\projects\\"; //assign a directory, be sure to escape the \

Console.WriteLine(FileExists(sFile));
Console.WriteLine(DirExists(sDir));
}

//-----------------------------------------------------------
// FUNCTION: DirExists
// Determines whether the specified directory name exists.
// IN: [sDirName] - name of directory to check for
// Returns: True if the directory exists, False otherwise
//-----------------------------------------------------------
private static bool DirExists(string sDirName) {
try {
return (System.IO.Directory.Exists(sDirName)); //Check for file
} catch (Exception) {
return (false); //Exception occured, return False
}
}

//-----------------------------------------------------------
// FUNCTION: FileExists
// Determines whether the specified file exists
// IN: [sPathName] - file to check for
// Returns: True if file exists, False otherwise
//-----------------------------------------------------------
private static bool FileExists(string sPathName) {
try {
return (System.IO.Directory.Exists(sPathName)); //Exception for folder
} catch (Exception) {
return (false); //Error occured, return False
}
}
}















 


© 2008-2009 dotnet4all.com