Friday, February 8, 2008

System.IO Namespace

Knowledge of working with streams is very essential. Make sure you master these skills before venturing into Cryptography, Compression, Serialization, etc.

File and Directory classes of System.IO namespace contains static method for working with Files and Directories.

Creating a text file and writing to it

The following example demonstrates the easiest way to create a file and writing into it using StreamWriter class.

using System.IO;
StreamWriter sw;

private void btnCreateText_Click(object sender, EventArgs e)
{
sw = File.CreateText(@"f:\ShalvinPD.txt");
sw.WriteLine("Shalvin P D");
sw.WriteLine("Web site : shalvin.com");
sw.Close();
}


Creating an Html Page on Fly

Certain job sites creates as web page for you based on the information you provided about yourself. Let's see how to do it in .Net.

StreamWriter sw;
private void btnCreateHtm_Click(object sender, EventArgs e)
{
sw = File.CreateText(@"f:\1Hello.htm");
sw.WriteLine("");
sw.WriteLine("");
sw.WriteLine("Shalvin P D");
sw.WriteLine("
");
sw.WriteLine("Web Site : shalvin.com");
sw.WriteLine("");
sw.WriteLine("");
sw.Close();
System.Diagnostics.Process.Start("iexplore", @"f:\1Hello.htm");
}

Listing All Drives
Listing all drives is as simple as creating an array of DriveInfo class, calling the DriveInfo.GetDrives methos and Iteraing throught the DriveInfo collection.

StreamWriter sw;
private void Form1_Load(object sender, EventArgs e)
{ DriveInfo[] diDrives = DriveInfo.GetDrives();
foreach (DriveInfo diDrive in diDrives)
listBox1.Items.Add(diDrive);
}

Retriving the Drive Type, Free Space and Total Size of Drives

StreamWriter sw;
private void Form1_Load(object sender, EventArgs e)
{try
{
DriveInfo[] diDrives = DriveInfo.GetDrives();
foreach (DriveInfo diDrive in diDrives)
{
listBox1.Items.Add(diDrive);
listBox1.Items.Add(String.Format("Drive Type : {0}", diDrive.DriveType)); listBox1.Items.Add(String.Format("Free Space : {0}", diDrive.AvailableFreeSpace)); listBox1.Items.Add(String.Format("Total Size : {0}", diDrive.TotalSize));
listBox1.Items.Add(" ");
}
}
catch (Exception ex) { }
}

Adding Line Numbers to a File


StreamReader sr = new StreamReader("c:\\Code.txt");
StreamWriter sw = new StreamWriter("c:\\S1.txt");
private void button1_Click(object sender, EventArgs e)
{
int i = 1;
while (! sr.EndOfStream)
{
string s = sr.ReadLine();
sw.WriteLine(i.ToString() + " " + s);
i++;
}
sw.Close();
System.Diagnostics.Process.Start("notepad", "c:\\S1.txt");
}



Related Blogs
.Net Serialization (Code Snippets)

Email : shalvin@gmail.com

1 comment: