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:
Opens the file if it exists and seeks to the end of the file, or creates a new file. This operation requires FileIOPermissionAccess.Append permission. FileMode.Append can be used only in conjunction with FileAccess.Write. Trying to seek to a position before the end of the file throws an IOException exception, and any attempt to read fails and throws an NotSupportedException exception.
So the if
statement is no longer need because FileMode.Append
automatically creates the file if it doesn't exist.
The complete solution would therefore be:
using (FileStream aFile = new FileStream(filePath, FileMode.Append, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(aFile)) {
sw.WriteLine(Empcode);
sw.WriteLine(fname);
sw.WriteLine(lname);
sw.WriteLine(ph);
sw.WriteLine("**********************************************************************");
}
Hint: use using
because it automatically closes the resources, also when an exception occurs.
You are creating the file if it exists, and appending if it doesn't. That's the opposite of what you want.
Change it to:
if (!File.Exists(filePath))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With