Sunday, August 15, 2010

Reading Data from the the file (.txt or .csv)

Using the File stream objects to read the data from a file
------------------------------------------------------------
ASSUMPTIONS MADE ARE: THE FILE NAME YOU ARE ENTERING IS EXISTING IN THE ROOT FOLDER OF YOUR APPLICATION. AND VALIDATIONS ARE TAKEN CARE BY YOU.


Code in the .ASPX file
------------------------


Code in .cs file
----------------
protected void btnReadFromFile_Click(object sender, EventArgs e)
{
//declaring the variables required

//we need to use System.IO name space for this.
System.IO.FileStream Fs = null;
System.IO.StreamReader Sr = null;
string tFilePath = string.Empty;
try
{
//gettting the file name as entered by the user
tFilePath = string.Concat(txtFileName.Text.ToString(), ".Txt");

//creating the file stream object
Fs = new System.IO.FileStream(Path.Combine(Server.MapPath("~/"), tFilePath), System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read);

//Reading the data into the file
Sr = new System.IO.StreamReader(Fs);
TxtTextToRead.Text = Sr.ReadToEnd();
//closing the streams
Sr.Close();
Fs.Close();

}
catch (Exception ex)
{
throw ex;
}
finally
{
//clearing the memory in the finally block
//Here first we need to close the streams and then make the objects to null
//other wise we get the error some times that the file is accessed by another program
Sr.Close();
Fs.Close();
if (Sr != null) Sr = null;
if (Fs != null) Fs = null;

}

}

1 comment:

  1. Server.MapPath("~/")
    The above code gives the application path ie., the root folder of the application.

    ReplyDelete