Wednesday, March 28, 2007

C# StreamReader and StreamWriter

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);
}
}
}
}

No comments: