[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Determine whether a file or directory exists in C#

[Determine whether a file or directory exists in C#]

It's usually more efficient to check whether a file or directory exists before you try to access it. For example, if you try to read a file that doesn't exist, the system needs to create error handling objects and a stack trace, and that takes extra time.

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

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 (Directory.Exists(txtDirectory.Text)) txtDirectoryResult.Text = "Yes"; else txtDirectoryResult.Text = "No"; } private void btnFileExists_Click(object sender, EventArgs e) { if (File.Exists(txtFile.Text)) txtFileResult.Text = "Yes"; else txtFileResult.Text = "No"; }

These event handlers just use the System.IO.Directory.Exists and System.IO.File.Exists methods to see if the directory and file exist. A simple but useful technique.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.