-----------------------------------------------------------------------------
ASSUMPTIONS MADE ARE:
THE VALIDATIONS ARE NOT DONE HERE, IT MUST BE TAKEN CARE BY YOU.
Code in the .ASPX page
-------------------------
Code in the .cs page
-----------------------
protected void btnWriteIntoFile_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.StreamWriter Sw = null;
string tFilePath = string.Empty;
try
{
//gettting the file name as entered by the user
tFilePath = string.Concat(txtFileName.Text.ToString(),".Txt"); //Change the ext as like(.Txt)
//creating the file stream object
Fs = new System.IO.FileStream(Path.Combine(Server.MapPath("~/"),tFilePath), System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite);
//writing the data into the file
Sw = new System.IO.StreamWriter(Fs) ;
Sw.Write(TxtTextToWriteData.Text.ToString());
//closing the streams
Sw.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
Sw.Close();
Fs.Close();
if (Sw != null) Sw = null;
if (Fs != null) Fs = null;
}
}

The above code has been written with the consideration of the optimal memory utilization. So the above code is a optimized code which is good in performance.
ReplyDelete