C# Folder Information
1. INTRODUCTION
In this tutorial we will create a program that extracts the contents of a folder in a text file. It will also optionally extract the extensions of the filenames and/or its subdirectories’ filenames.
The first thing to do is create a visual c# windows form project. The IDE should initially look like picture 1.
2. GUI
The first thing one should do, is to create the graphical user interface such as the one in pictures 2 and 3. The three buttons will perform the same actions with the menu bar. The first checkbox will be used to control whether the output will include all subdirectories of the chosen path or only the files specified in the current directory. The second one controls the extraction of the filename extension. At the end of this tutorial the form should look like Pictures 2 and 3.
Insert a menu bar and a status bar. You can insert them by double clicking the appropriate controls (
menu-strip and
status-strip) from the category “
Menus & Toolbars” of the ToolBox. Insert (with a double click) a button control. Do this three times since we need three of them. The button control is located in the “
Common Controls” category. From the same category insert two checkboxes and a textbox. Set the “
Multiline” property of the textbox to “
TRUE” and the “
Enabled” property to “
False”. Finally, add a vertical scrollbar (from the properties menu) to the textbox. Place the objects as Picture 3 indicates and change their “
Text” property to the text shown in each control.
The form must remain in a fixed size or we risk ruining the alignment of the objects. Therefore, click once on the form and then set the property “
Maximize Box” to “
False” and the “
FormBorderStyle” to “
Fix3D”.
To finalize the user interface we now enter the menustrip values. Click once on the menustrip control. Click on the smart tag glyph on the upper right corner once and select “
Edit Items”(see Picture 5). The
Items Collection Editor is now open.
For this project we will need one menu item called “
File…” with three drop-down button items that will perform the same operations with the three other buttons on the form. To place a menu item press “
Add” on the
Items Collection Editor. Change its name to “FILEtoolStripMenuItem” and its text value to “
File…”. To create the drop-down items go to the property named “
DropDownItems” and press its corresponding button (…) to proceed as Picture 6 shows.
A new
Items Collection Editor has now opened. It will include all the drop-down buttons for the menu item “
File…”. We need three such controls so press three times the “
Add” button to add the three menu items. Change their text properties to “
Open directory”, ”
Extract to Output” and ”
Close Program” accordingly, as picture 7 indicates. Finally set the property “
Enabled” of the two “
Extract to Output” controls(menu item + button) to “
False”.
Now, press F5 to run the program and see if the form corresponds to the one we created up to this point. It should look similar to this:
Press once on the toolstrip control and press the arrow to add a “ToolStripStatusLabel” as picture 9 illustrates. Set its “Text” property to “”.
3. CODE
It is now time to proceed to the code development phase. In this phase we will create code that extracts the filenames of all files in a specified folder in a text file. If the first checkbox is checked, then our code will enter all subdirectories of the specified folder and extract its filenames also. Otherwise, it will extract only the filenames inside the selected folder. Checking the second checkbox will result in an output of the form “
Name.Ext” instead of only the file name. The procedure will be the following one:
- The user first has to check or uncheck the two checkboxes.
- User clicks on one of the two Open Directory buttons. A Folder browsing dialog appears and the user selects a folder.
- The filenames appear to the textbox. The “Extract to Output” controls are enabled.
- Pressing one of the “Extract to Output” buttons will open a save file dialog. The user can then enter a filename to save the filenames in text format.
Double click on the
FolderBrowserDialog and on the
SaveFiledialog on the ToolBox under the “
Dialog” category. You will not see any controls on the form for these two dialogs. You must now create a subroutine that extracts all filenames to the textbox. When the user clicks on the appropriate button the subroutine is called. Double click the button1. Copy the following code to its subroutine button1_Click:
Code:
private void button1_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Enabled = true;
textBox1.Text = "";
toolStripMenuItem2.Enabled = true;
button2.Enabled = true;
DirectoryInfo myDir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
toolStripStatusLabel1.Text = myDir.ToString();
ShowFiles(myDir);
if (checkBox1.Checked == true)
{
foreach (DirectoryInfo SubDir in myDir.GetDirectories())
{
ShowFiles(SubDir);
}
}
}
}
This code presents a dialog to select a folder, and if it was correctly used it performs the following actions:
- Enables the textbox and the buttons for extracting the data to files.
- Clears the textbox’s text.
- Creates a DirectoryInfo class object set to the selected folder to iterate through files and directories.
- Sets the status strip label to display the selected folder.
- Calls the subroutine for extraction of filenames.
- If the checkbox2 is checked, calls the subroutine with each subdirectory as parameter.
Now we create the subroutine called
Showfiles with one
DirectoryInfo object as a parameter. Copy the following code to your data:
Code:
private void ShowFiles(DirectoryInfo mySecondDir)
{
string myPath = "";
foreach (FileInfo file in mySecondDir.GetFiles())
{
myPath = file.ToString();
if (checkBox1.Checked == true )
textBox1.Text = textBox1.Text + Path.GetFileNameWithoutExtension(myPath) + Environment.NewLine;
else
textBox1.Text = textBox1.Text + Path.GetFileNameWithoutExtension(myPath) + Environment.NewLine;
}
}
This snippet of code iterates through each file in the passing folder parameter and extracts its filenames either with or without the extension on the textbox. Test your code to see if it is working correctly.
The final step is to create a file to write the contents of the textbox. The following code does exactly this. Paste it to button2 code:
Code:
private void button2_Click(object sender, EventArgs e)
{
saveFileDialog1.Filter = "Text file | *.txt";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
FileStream myFile = (FileStream)saveFileDialog1.OpenFile();
StreamWriter myStream = new StreamWriter(myFile);
myStream.Write(textBox1.Text);
myStream.Close();
myFile.Close();
}
}
A
saveFile dialog appears and if the user selects a filename then a filestream and a streamwriter that join the textbox’s contents with the file are created. Then, the contents of the textbox are written on the selected file. After this, the FileStream and StreamWriter objects are closed.
Lastly, the button3 that closes the program should contain the following line of code:
Code:
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
The final step is to copy the code of the form buttons on the Menustrip items. You have now completed the tutorial, run the program in debug mode and verify its operation.
Questions/Comments?
If you have questions or comments about this tutorial please post them here.