The
StreamWriter is used to write data to the hard disk. The data may be in the form of Strings, Characters, Bytes etc. Also you can specify he type of encoding that you are using. The Constructor of the
StreamWriter class takes basically two arguments: The first one is the actual file path with file name that you want to write & the second one specifies if you would like to replace or overwrite an existing file.The
StreamWriter creates objects that have interface with the actual files on the hard disk and enable them to be written to text or binary files. In this example we write a text file to the hard disk whose location is chosen through a save file dialog box.
The file path can be easily chosen with the help of a save file dialog box(SFD). If the file already exists the default mode will be to append the lines to the existing content of the file. The data type of lines to be written can be specified in the parameter supplied to the Write or Write method of the StreaWriter object. Therefore the Write method can have arguments of type Char, Char[], Boolean, Decimal, Double, Int32, Int64, Object, Single, String, UInt32, UInt64.
using
System;
namespace StreamWriter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void
btnChoosePath_Click(object sender, EventArgs e)
{
if (SFD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txtFilePath.Text = SFD.FileName;
txtFilePath.Text += ".txt";
}
}
private void
btnSaveFile_Click(object sender, EventArgs e)
{
System.IO.StreamWriter objFile =
new System.IO.StreamWriter(txtFilePath.Text,true);
for (int i = 0; i
< txtContents.Lines.Length; i++)
{
objFile.WriteLine(txtContents.Lines[i].ToString());
}
objFile.Close();
MessageBox.Show("Total
Number of Lines Written : " +
txtContents.Lines.Length.ToString());
}
private void
Form1_Load(object sender, EventArgs e)
{
// Anything
}
}
}
Please Note :
** Do not Copy & Paste code written here ; instead type it in your Development Environment
** Testing done in .Net Framework 4.5 but code should be very similar for previous versions of .Net
** All Program Codes here are 100% tested & running.
** Do not Copy & Paste code written here ; instead type it in your Development Environment
** Testing done in .Net Framework 4.5 but code should be very similar for previous versions of .Net
** All Program Codes here are 100% tested & running.