Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

- - - - -

Tutorial: Visual Studio 2008 C# Folder Information

visual studio 2008 streamwriter

  • Please log in to reply
9 replies to this topic

#1 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 19 May 2008 - 02:55 PM

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.

Posted Image


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.

Posted Image

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.


Posted Image

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.

Posted Image

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.

Posted Image

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”.

Posted Image

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:

Posted Image

Press once on the toolstrip control and press the arrow to add a “ToolStripStatusLabel” as picture 9 illustrates. Set its “Text” property to “”.


Posted Image


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:

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:

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:

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:

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.
  • 0

#2 Xav

Xav

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 8356 posts

Posted 20 May 2008 - 12:05 PM

It just shows how useful the .NET Framework can be. Also, it allows VB.NET to do the same thing, with just a slightly different syntax.
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#3 Don

Don

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 27 October 2009 - 06:46 PM

Hi Jordan:
I am working through your tutorials and am finding them very instructive and informativel, thank you. Followed the tutorial below and debugged as per instructions. Received an error:
The type or namespace name "DirectoryInfo" could not be found (are you missing a using directice or an assembly reference?).
Any help would be appreciated.
Regards,
Don
  • 0

#4 technica

technica

    CC Regular

  • Just Joined
  • PipPipPip
  • 43 posts

Posted 27 October 2009 - 11:05 PM

Nice article, and thank you for posting it. It will surly help us all.
  • 0

#5 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 28 October 2009 - 04:13 AM

Hi Jordan:
I am working through your tutorials and am finding them very instructive and informativel, thank you. Followed the tutorial below and debugged as per instructions. Received an error:
The type or namespace name "DirectoryInfo" could not be found (are you missing a using directice or an assembly reference?).
Any help would be appreciated.
Regards,
Don


DirectoryInfo is part of the System.IO class. you can add "using System.IO" at the top, above your class or express the full namespace when using DirectoryInfo:
System.IO.DirectoryInfo myDir = new System.IO.DirectoryInfo(folderBrowserDialog1.SelectedPath);

  • 0

#6 Don

Don

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 28 October 2009 - 08:22 AM

Thank you for your prompt response, corrected problem immediately. I appreciate the straightforward answer, no snide remarks or words of wisdom, how refreshing. So you know, I did some additional research (not a complete slacker), pretty common error/omission for a newbie such as myself. Thanks again! - Don
  • 0

#7 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 28 October 2009 - 08:46 AM

Great, glad it helped. :)
No worries, I know how frustrating it can be to get answers when you first begin learning something. Feel free to stick around and ask any other questions in the appropriate sections.
  • 0

#8 gaylo565

gaylo565

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 258 posts

Posted 28 October 2009 - 10:08 AM

Nice tut! Very thorough and nicely put together. I like that you cover a topic wich has many different uses in applications as well.
  • 0

#9 debtboy

debtboy

    CC Devotee

  • Just Joined
  • PipPipPipPipPipPip
  • 499 posts

Posted 28 October 2009 - 07:20 PM

Great Tutorial +rep
  • 0

#10 Unknown_Error

Unknown_Error

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 02 January 2012 - 02:24 PM

Hello

I was browsing through this thread and wanted to know whether or not you could help me. I am constructing a simple program that shows several pieces of data about a file. Can you please tell me how to quit a program with the press of a button. So if I pressed q to quit then tell me how to do that in C#. Folder information, how to display information about a specific folder. So information like the number of files in: C//Windows, total files, total file sizes, small/largest file and so on. I've tried this, but all I keep getting is DirectoryInfo does not contain a definition. Also, how about filters?

So, if you could tell me how to do these things in C#, I would be grateful:

FolderInfo - The info about a folder and the properties of that folder.
End Program - How to end the program on a press of a button.
Filters - How to filter a list of files to only show specific file formats such as doc, exe and so on.

Keep in mind that I use a console program in C# 2008

Any help would be extremely appreciated.

Best Regards
  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download