SIGN UP MEMBER LOGIN:    
ARTICLE

File Reader & Writer and File Open Dialog & Folder Open Dialog in C# - Part 2

Posted by Sivaraman Dhamodaran Articles | Windows Forms C# January 11, 2011
This is second part of the article that covers FolderBrowserDialog and using the StreamWriter to write a text content into a file.
Reader Level:
Download Files:
 

1. Introduction

In the previous part we saw how to use FileOpen dialog and then read the text content using the StreamReader object. Also we saw an important FileOK event handler where we can to validation for the selected file. This article is the continuation to the previous article, but you can still read it and know the usage of the Folder open dialog and StreamWriter object.

You can read the previous part from here

The screen shot is shown here for the continuation.

Pic01.JPG 

2. Save File button Handler

1) First, drag and drop the FolderBrowserDialog component (Control) from the toolbox to the form. Set the properties for the control by referring the downloaded application. This component can be found under the dialogs group in your toolbox. Once this is done provide the handler for Save File button.

The description property of the FolderBrowserDialog set the heading for the dialog. You can place a informative text to help the user to make their folder selection. As we are going to save the text file under the selected folder, I kept the text relevant to that. The RootFolder property is used to set the topmost node of tree display of the directory. Below is the code:

//001: Setup the Folder dialog properties before the display

string selected_path = "";

dlgFolder.Description = "Select a Folder for Saving the text file";

dlgFolder.RootFolder = Environment.SpecialFolder.MyComputer; 

2) Once the RootFolder for the Folder dialog is set, display the dialog using the ShowDialog() method. The return value is tested to tell, how the dialog closed by the end user. Once we make sure a folder is selected and clicking the OK button closed the dialog, we store the selected folder under a local variable using the SelectedPath property of the FolderBrowserDialog. 

//002: Display the dialog for folder selection

if (dlgFolder.ShowDialog() == DialogResult.OK)

{

    selected_path = dlgFolder.SelectedPath;

    if (string.IsNullOrEmpty(selected_path) == true)

    {

        MessageBox.Show("Unable to save. No Folder Selected.");

        return;

    }

}

Pic04.JPG 

3) Finally, we make sure the displayed content is text. And make a call to the SaveFile function written for this form. The function accepts the path as parameter and then saves the file in the specified path by taking the file name from the relevant text box. 

//003: Perform the File saving operation. Make sure text file is displayed before saving.

if (txtFileContent.Visible == true)

{

    SaveFile(selected_path);

}

else

    MessageBox.Show("This form saves only text files"); 

4) The SaveFile() function first checks the selected path is a root folder (Partition itself. Ex: C:\ or D:\). And based on the test appends a slash at the end of the path. (Debug it to see why?). Then a FileStream object for the given file is created with the path selected by the folder dialog. Note that, this time in the constructor for the FileStream we asked to create a new file using FileMode.CreateNew enumerated constant. Once the FileStream is ready is connected to the StreamWriter for the writing the text content displayed in the multi-select text box. Using the Write () method on the StreamWriter entire content of the Multi-line textbox is written in the Specified text file. The saved path is displayed in the Label at the bottom of the form. 

//File 005: Save the File to Disk

private void SaveFile(string selected_path)

{

    string Save_File;

    if (selected_path.Length > 3)

        Save_File = selected_path + "\\" + txtSaveFile.Text + ".txt";

    else

        Save_File = selected_path + txtSaveFile.Text + ".txt";

    FileStream fstream = new FileStream(Save_File, FileMode.CreateNew);

    StreamWriter writer = new StreamWriter(fstream);

    writer.Write(txtFileContent.Text);

    lblSavedLocation.Text = "Text File Saved in " + Save_File;

    writer.Close();

} 

3. Save in Temp Path Handler 

This button handler just makes a call to the SaveFile function by passing the system's temporary path. The method GetTempPath() of the utility class Path will return the temporary path. Hope, no more explanation is required on this simple function. 

//File 004: Save the File in System Temporary path

private void btnTempPath_Click(object sender, EventArgs e)

{

    if (txtFileContent.Visible == true)

    {

        SaveFile(Path.GetTempPath());

    }

    else

        MessageBox.Show("This form saves only text files");

} 

Note: The application is created in Visual Studio 2005. If you have latest IDE say "Yes" conversion Wizard/Dialog that appears. To know how the Form work read the previous part also.

Login to add your contents and source code to this article
share this article :
post comment
 

Hi.... I'm creating window application in C#.net Please Tell me how to upload file and store path of the file in database and copy the file in folder.. upload any type of file.. .pdf,.doc.,.zip,.rar.. etc... if demo is possible so..... Hop for favorable Responce... Thanks In Advance...

Posted by Chirag Makwana Feb 28, 2011

Sam! This is about FolderBrowserDialog and StreamWriter. The previous part is for FileOpenDialog and StreamReader. Thank you.

Posted by Sivaraman Dhamodaran Jan 12, 2011

I am confused; is this article about the FileOpen dialog or the OpenFileDialog class or the FolderBrowserDialog class. The sample dialog that is shown is not a FolderBrowserDialog but the remaining article seems to describe the FolderBrowserDialog class. If this article is about the FolderBrowserDialog class then it would help if the introduction explains that.

Posted by Sam Hobbs Jan 12, 2011
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor