You can simply call
using (StreamWriter w = File.AppendText("log.txt"))
It will create the file if it doesn't exist and open the file for appending.
Edit:
This is sufficient:
string path = txtFilePath.Text;
using(StreamWriter sw = File.AppendText(path))
{
foreach (var line in employeeList.Items)
{
Employee e = (Employee)line; // unbox once
sw.WriteLine(e.FirstName);
sw.WriteLine(e.LastName);
sw.WriteLine(e.JobTitle);
}
}
But if you insist on checking first, you can do something like this, but I don't see the point.
string path = txtFilePath.Text;
using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))
{
foreach (var line in employeeList.Items)
{
sw.WriteLine(((Employee)line).FirstName);
sw.WriteLine(((Employee)line).LastName);
sw.WriteLine(((Employee)line).JobTitle);
}
}
Also, one thing to point out with your code is that you're doing a lot of unnecessary unboxing. If you have to use a plain (non-generic) collection like ArrayList
, then unbox the object once and use the reference.
However, I perfer to use List<>
for my collections:
public class EmployeeList : List<Employee>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…