i have written the following code to append the data with existing data as it is but my code overwrite this
what should i do the changes to code append data.
protected void Page_Load(object sender, EventArgs e)
{
fname = Request.Form["Text1"];
lname = Request.Form["Text2"];
ph = Request.Form["Text3"];
Empcode = Request.Form["Text4"];
string filePath = @"E:Employee.txt";
if (File.Exists(filePath))
{
//StreamWriter SW;
//SW = File.CreateText(filePath);
//SW.Write(text);
//SW.Close();
FileStream aFile = new FileStream(filePath, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(aFile);
sw.WriteLine(Empcode);
sw.WriteLine(fname);
sw.WriteLine(lname);
sw.WriteLine(ph);
sw.WriteLine("**********************************************************************");
sw.Close();
aFile.Close();
}
else
{
//sw.Write(text);
//sw.Flush();
//sw.Close();
//StreamWriter SW;
//SW = File.AppendText(filePath);
//SW.WriteLine(text);
//SW.Close();
FileStream aFile = new FileStream(filePath, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(aFile);
sw.WriteLine(Empcode);
sw.WriteLine(fname);
sw.WriteLine(lname);
sw.WriteLine(ph);
sw.WriteLine("**********************************************************************");
sw.Close();
aFile.Close();
//System.IO.File.WriteAllText(filePath, text);
}
Response.Write("Employee Add Successfully.........");
}
The doc for FileMode.Append says:
So the
ifstatement is no longer need becauseFileMode.Appendautomatically creates the file if it doesn’t exist.The complete solution would therefore be:
Hint: use
usingbecause it automatically closes the resources, also when an exception occurs.