Things You'll Need:
- Microsoft Visual C# 2008 Express (free)
-
Step 1
Note: This article assumes you have installed Microsoft Visual C# 2008 Express Edition. You may download it for free from here: http://www.microsoft.com/express/download/
Open Microsoft Visual C#. Click on "Project..." to the right of Create in the Recent Projects area of the Start Page.
The New Project window will open. Click on "Windows Forms Application", enter a Name, and click OK.
By default, the only form in the project will be called "Form1" and you will be in Design mode for that form. -
Step 2
Hover over the Toolbox on the left side of the screen and the Toolbox will automatically expand. Click and drag a Button control, under the Common Controls category, onto the form.
-
Step 3
Double click the button and you will now be in the code window for Form1. The method for the button click will already be created.
-
Step 4
Add "using System.IO;" just beneath "using System.Windows.Forms;". This namespace contains the Directory object that has the GetFiles method that we will be using.
-
Step 5
In the button1_Click method, place the following code:
string MyDirectory = "C:\\";
string MyString = "My Files: ";
try{
string [] MyFiles = Directory.GetFiles( MyDirectory, "*", SearchOption.TopDirectoryOnly );
foreach( string MyFile in MyFiles )
{
MyString = MyString + MyFile + "; ";
}
MessageBox.Show( MyString );
}
catch(Exception MyError){
MessageBox.Show("Error reading file: "+ MyError.Message);
}
The try/catch statements will capture any error that occurs and will pop-up a MessageBox with the error displayed.
The method Directory.GetFiles takes a string for the directory, a pattern-matching string, and a flag for whether or not the sub-directories should be included. The pattern "*" will match any file in the directory. The two options you can use for the flag are:
SearchOption.AllDirectories - Search all sub-directories.
SearchOption.TopDirectoryOnly - Search only this directory.
Since we are using "C:\" for our directory, searching the sub-directories would be a bad idea.
Directory.GetFiles returns an array of strings where each element is the name of a file in that directory. Then we loop through the array using a foreach loop and append the name of the file to the MyString string. Once we have looped through all of the files, we display the MyString in a MessageBox. -
Step 6
Go up to the toolbar and run the program by clicking on the Start Debugging (f5) play button.
NOTE: If you got any kind of error after clicking the play button, you probably made a syntax error when typing the code. Reread the code until you find and correct the error and try again. -
Step 7
The form will take a moment and then pop up. Click on the button and you will get a pop-up with your files listed. Awesome!















