如果文件不存在,我需要读取我的代码以创建else append。现在它正在阅读,如果它存在创建和追加。这里是代码:如果文件不存在,创建文件
if (File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
我会这样做吗?
if (! File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
编辑:
string path = txtFilePath.Text;
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
foreach (var line in employeeList.Items)
{
sw.WriteLine(((Employee)line).FirstName);
sw.WriteLine(((Employee)line).LastName);
sw.WriteLine(((Employee)line).JobTitle);
}
}
}
else
{
StreamWriter sw = File.AppendText(path);
foreach (var line in employeeList.Items)
{
sw.WriteLine(((Employee)line).FirstName);
sw.WriteLine(((Employee)line).LastName);
sw.WriteLine(((Employee)line).JobTitle);
}
sw.Close();
}
}
[File.AppendAllText](HTTP:// MSDN .microsoft.com/en-us/library/ms143356.aspx) - 这正是您在一行代码中所需要的。 –
@ShadowWizard由于被标记的作业OP可能实际上被引导以显示条件逻辑。 – Yuck
@Yuck - 家庭作业重新发明轮子?呸! ;) –