Sunday, April 6, 2008

System.IO Namespace in .Net

Streams are the means for reading from and writing to the disk and communicating across the network.
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();
}


















StreamReader class for reading from a file










StreamReader sr = new StreamReader("f:\\ShalvinPD.txt");
txtData.Text = sr.ReadToEnd();



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.

using System.IO;







Creating an Asp .Net Page on Fly






Creating, Deleting and Checking for the existence of a Directory

Directory class can be used for typical operations such as copying, moving, renaming, creating, and deleting directories.
private void btnCreate_Click(object sender, EventArgs e)
{
Directory.CreateDirectory("c:\\Shalvin");

}

private void btnExist_Click(object sender, EventArgs e)
{
if (Directory.Exists("c:\\Shalvin"))
MessageBox.Show("Directory exist");
else
MessageBox.Show("Directory doesn't exist");
}

private void btnDeletingDirectory_Click(object sender, EventArgs e)
{
if (Directory.Exists("c:\\Shalvin"))
{
Directory.Delete("c:\\Shalvin");
MessageBox.Show("Directory deleted successfully");
}
else
MessageBox.Show("Directory doesn't exist");
}
}

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

Writing to a BinaryFile using BinaryWriter Class







BinaryReader and BinaryWriter Classes can be used to store and retrieve primitive datatypes like Integer, string, etc. as binary file.








using System.IO;


BinaryWriter objBinaryWriter;
BinaryReader br;
FileStream fs;

private void btnCreate_Click(object sender, EventArgs e)
{
try
{
fs = new FileStream(@"c:\Shalvin.data", FileMode.Create);
objBinaryWriter = new BinaryWriter(fs);


objBinaryWriter.Write(98);
objBinaryWriter.Write(88);
objBinaryWriter.Write(99);

objBinaryWriter.Close();
fs.Close();

MessageBox.Show("Binary file created successfully");
}
catch (IOException ioe)
{
MessageBox.Show("Device is not ready");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}




































Adding Line Number to a File

using System.IO;


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

































































Picture Viewer

































using System.IO;
using System.Collections;

ArrayList al = new ArrayList();



int i;
private void Form1_Load(object sender, EventArgs e)
{
DirectoryInfo di = new DirectoryInfo("c:\\");
FileInfo[] fi = di.GetFiles();
foreach (FileInfo f in fi)
if (f.Extension == ".jpg")
{
listBox1.Items.Add(f.FullName);
al.Add(f.FullName);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e){
pictureBox1.Load(listBox1.Text);
}
private void btnNext_Click(object sender, EventArgs e)
{
if (i < al.Capacity - 1)
{
pictureBox1.Load(al[i].ToString());
i++;
}
else
MessageBox.Show("End of file");
}






Generating Text File from Database Table






using System.Data.SqlClient;
using System.IO;




SqlConnection cnn;
SqlCommand cmd;
SqlDataReader dr;
StreamWriter sw = new StreamWriter("c:\\Categories.txt");
private void Form1_Load(object sender, EventArgs e)
{
cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind");
cnn.Open();
cmd = new SqlCommand("select * from Products", cnn);
dr = cmd.ExecuteReader();
while (dr.Read())
sw.WriteLine(String.Format("{0} \t {1} ", dr["ProductId"], dr["ProductName"].ToString()));
sw.Close();
System.Diagnostics.Process.Start("notepad", "c:\\Categories.txt");
}

VB.Net


Imports System.Data.SqlClient
Imports System.IO
Imports System.Diagnostics


Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim dr As SqlDataReader
Dim sw As New StreamWriter("c:\\Products.txt")
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cnn = New SqlConnection("Integrated security=sspi;Initial Catalog=Northwind")
cnn.Open()
cmd = New SqlCommand("select * from products", cnn)
dr = cmd.ExecuteReader
While (dr.Read())
sw.WriteLine(String.Format("{0} {1} {2} {1} {3}", dr("ProductID"), vbTab, dr("ProductName"), dr("UnitPrice")))
End While
sw.Close()
Process.Start("notepad", "c:\\Products.txt")
End Sub


Output






















Parsing a Tab Delimited Text File





using System.IO;
StreamReader sr = new StreamReader("c:\\Categories2.txt");
private void Form1_Load(object sender, EventArgs e)
{
while (!sr.EndOfStream)
{
string s = sr.ReadLine();
string[] sa = s.Split('\t');
listBox1.Items.Add(sa[0]);
listBox2.Items.Add(sa[1]);
listBox3.Items.Add(sa[2]);
}
}

VB .Net

Imports System.IO

Dim sr As New StreamReader("c:\\Produc.txt")
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
While Not sr.EndOfStream
Dim s As String = sr.ReadLine
Dim sa() = s.Split(vbTab)
ListBox1.Items.Add(sa(0))
ListBox2.Items.Add(sa(1))
ListBox3.Items.Add(sa(2))
End While
End Sub

Related Blogs






Isolated Storage (Code Snippets)







.Net Serialization







1 comment:

  1. Can anyone recommend the top Remote Management program for a small IT service company like mine? Does anyone use Kaseya.com or GFI.com? How do they compare to these guys I found recently: N-able N-central service desk
    ? What is your best take in cost vs performance among those three? I need a good advice please... Thanks in advance!

    ReplyDelete