Friday, July 31, 2009

Writing and Reading to a Text File.

Writing and Reading to a Text File:


Description:


When developers have large data in text box then it is not possible to insert into a database table.
So you can use the below code to write to a text and save file path in the database. So to read
a file use the below code by passing the file path.



Design View:




Code Behind:



//.....Below Method is for writing data from a textbox to a text file.


protected void WritingToTextFile()
{

//.....Generating a file name.

string concatstring = DateTime.Now.ToString("ddMMyyyy")+" "+DateTime.Now.Hour.ToString()+""+DateTime.Now.Minute.ToString()+""+DateTime.Now.Second.ToString()+""+DateTime.Now.Millisecond.ToString();
string fname = concatstring+".txt";
string filename = "D:\\"+concatstring+".txt";

//.....FileInfo class is for creating file.

FileInfo fnew = new FileInfo(filename);

//.....StreamWriter class is for writing text to the text file.

StreamWriter sw = fnew.CreateText();
sw.WriteLine(txtTemplate.Text);
sw.Close();
}

protected void ReadingTextFile(string sFileName)
{
string sframedata = "";
string datas = "";

//.....StreamReader class is for Reading text from the text file.

StreamReader sr = new StreamReader("D:\\"+sFileName);
while((datas = sr.ReadLine()) != null)
{
sframedata += datas;
}
txtTemplate.Text = sframedata.ToString();
}

Regard

Prateek

No comments:

Post a Comment