Determine whether a file or directory exists in C#

When the program starts, it uses the following code to initialize its TextBoxes.

private void Form1_Load(object sender, EventArgs e)
{
    txtDirectory.Text = Application.StartupPath;
    txtDirectory.Select(txtDirectory.Text.Length, 0);

    txtFile.Text = Application.ExecutablePath;
    txtFile.Select(txtFile.Text.Length, 0);
}

This code displays the startup directory in the Directory TextBox and the executable program's name in the File TextBox. When you click the buttons, the following event handlers execute.

private void btnDirectoryExists_Click(object sender, EventArgs e)
{
    if (System.IO.Directory.Exists(txtDirectory.Text))
        txtDirectoryResult.Text = "Yes";
    else txtDirectoryResult.Text = "No";
}

private void btnFileExists_Click(object sender, EventArgs e)
{
    if (System.IO.File.Exists(txtFile.Text))
        txtFileResult.Text = "Yes";
    else txtFileResult.Text = "No";
}

These event handlers just use System.IO.Directory.Exists and System.IO.File.Exists to see if the directory and file exist.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.