C# StreamReader and StreamWriter Explained - Using StreamWriter to write to a file
(Page 2 of 4 )
You can have a StreamWriter object as the return value from calling the method File.CreateText(). You can also create a StreamWriter object using one of its constructor overloads. The following example illustrates using a StreamWriter object with a FileStream object to write characters to the file aFile.txt
using System;
using System.IO;
namespace MyStreams
{
class Class1
{
public static void Main()
{
try
{
FileStream fs = new FileStream
("aFile.txt",FileMode.Create,
FileAccess.ReadWrite,FileShare.None);
string[] strings = {"C#", "ASP.NET", "XML"};
using(StreamWriter sw = new StreamWriter(fs))
{
Console.WriteLine("This StreamWriter instance uses {0}
to write to the file", sw.BaseStream);
Console.WriteLine("The Property sw.Encoding returns:
{0}",sw.Encoding);
sw.WriteLine("www.aspfree.com");
sw.WriteLine("contains many useful articles");
sw.WriteLine("on many different technologies like {0},
{1} and {2}", strings);
}
Console.WriteLine("Data has been written to the file");
Console.ReadLine();
}
catch(IOException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Copy the above code and paste it in place of the auto-generated code of Class1.cs in your project, then run it and you will get the following screen shot:

Navigate to the folder of the application to open the file aFile.txt.

As you can see, there are three text lines written to this file. Let's walk through the code step-by-step
Next: Step-by-step through the code example >>
More C# Articles
More By Michael Youssef