+ Reply to Thread
Results 1 to 10 of 10

Thread: Tutorial: Visual Studio 2008 C# Folder Information

  1. #1
    Jordan Guest

    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.

  2. CODECALL Circuit advertisement

     
  3. #2
    Join Date
    Mar 2008
    Location
    The North Pole
    Posts
    13,174
    Blog Entries
    13
    Rep Power
    114

    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.

    Quote Originally Posted by Jordan View Post
    Good members, like yourself, stick around and post for ages to come!
    Mr. Xav | Blog | Forums

  4. #3
    Don
    Don is offline Newbie
    Join Date
    Oct 2009
    Posts
    2
    Rep Power
    0

    Re: Tutorial: Visual Studio 2008 C# Folder Information

    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

  5. #4
    technica's Avatar
    technica is offline Learning Programmer
    Join Date
    Oct 2009
    Posts
    64
    Rep Power
    0

    Re: Tutorial: Visual Studio 2008 C# Folder Information

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

  6. #5
    Jordan Guest

    Re: Tutorial: Visual Studio 2008 C# Folder Information

    Quote Originally Posted by Don View Post
    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:
    Code:
    System.IO.DirectoryInfo myDir = new System.IO.DirectoryInfo(folderBrowserDialog1.SelectedPath);

  7. #6
    Don
    Don is offline Newbie
    Join Date
    Oct 2009
    Posts
    2
    Rep Power
    0

    Re: Tutorial: Visual Studio 2008 C# Folder Information

    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

  8. #7
    Jordan Guest

    Re: Tutorial: Visual Studio 2008 C# Folder Information

    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.

  9. #8
    gaylo565's Avatar
    gaylo565 is offline Programming Professional
    Join Date
    May 2007
    Location
    flagstaff, az
    Posts
    268
    Rep Power
    21

    Re: Tutorial: Visual Studio 2008 C# Folder Information

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

  10. #9
    Join Date
    Aug 2009
    Location
    ~/
    Posts
    918
    Rep Power
    19

    Re: Tutorial: Visual Studio 2008 C# Folder Information

    Great Tutorial +rep

  11. #10
    Unknown_Error is offline Newbie
    Join Date
    Jan 2012
    Posts
    1
    Rep Power
    0

    Re: Tutorial: Visual Studio 2008 C# Folder Information

    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

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Tutorial: Visual Studio 2008 C# Serialization
    By Jordan in forum CSharp Tutorials
    Replies: 3
    Last Post: 01-10-2012, 07:49 PM
  2. Visual Studio 2008: C# Hello World Tutorial
    By Jordan in forum CSharp Tutorials
    Replies: 32
    Last Post: 07-30-2010, 07:15 AM
  3. Replies: 0
    Last Post: 03-21-2010, 09:29 AM
  4. Replies: 10
    Last Post: 09-25-2009, 05:28 AM
  5. Tutorial: Visual Studio 2008 C# Compressing
    By Jordan in forum CSharp Tutorials
    Replies: 5
    Last Post: 08-30-2009, 05:25 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts