Lost Password?


  #1 (permalink)  
Old 05-19-2008, 06:55 PM
Jordan's Avatar   
Jordan Jordan is offline
Administrator
 
Join Date: Nov 2005
Location: Hendersonville, NC
Posts: 9,224
Last Blog:
Ext JS or Ext GWT
Rep Power: 20
Jordan is just really niceJordan is just really niceJordan is just really niceJordan is just really nice
Send a message via ICQ to Jordan Send a message via AIM to Jordan Send a message via MSN to Jordan
Default Tutorial: Visual Studio 2008 C# Folder Information

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:

  1. The user first has to check or uncheck the two checkboxes.
  2. User clicks on one of the two Open Directory buttons. A Folder browsing dialog appears and the user selects a folder.
  3. The filenames appear to the textbox. The “Extract to Output” controls are enabled.
  4. 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.
__________________
CodeCall Blog | CodeCall Wiki | Shareware Site | Linux Forum | Write a Blog
The CodeCall Wiki is now fully integrated with vBulletin users! Check it out and add some new pages!
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

Sponsored Links
  #2 (permalink)  
Old 05-20-2008, 04:05 PM
Xav's Avatar   
Xav Xav is offline
Code Warrior
 
Join Date: Mar 2008
Location: On God's Planet
Posts: 9,589
Last Blog:
Web slideshow in JavaS...
Rep Power: 76
Xav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud of
Send a message via MSN to Xav
Default Re: Tutorial: Visual Studio 2008 C# Folder Information

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


Mr. Xav | Website | Forums | Blog
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply

Tags
c# tutorial, directory, folder, information



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Visual Studio 2008: C# Hello World Tutorial Jordan CSharp Tutorials 14 11-20-2008 02:53 PM
Tutorial: Visual Studio 2008 Obfuscating with Dotfuscator Jordan Tutorials 5 11-16-2008 03:05 PM
Visual Studio 2008 SP1 "Background Compiling" for C# Kernel Programming News 3 05-14-2008 03:51 PM
Tutorial: Visual Studio 2008 C# Compressing Jordan CSharp Tutorials 0 05-13-2008 05:52 PM


All times are GMT -5. The time now is 11:22 AM.

Contest Stats

WingedPanther ........ 2753.6
Xav ........ 2704
Brandon W ........ 1702.32
John ........ 1207.73
marwex89 ........ 1175.24
morefood2001 ........ 966.05
dcs ........ 655.75
Steve.L ........ 475.59
orjan ........ 418.58
Aereshaa ........ 383.54

Contest Rules

CodeCall Goal

Goal: 100,000 Posts
Complete: 97%

Ads