2012-04-30 37 views
37

如果文件不存在,我需要读取我的代码以创建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(); 
} 

}

+1

[File.AppendAllText](HTTP:// MSDN .microsoft.com/en-us/library/ms143356.aspx) - 这正是您在一行代码中所需要的。 –

+0

@ShadowWizard由于被标记的作业OP可能实际上被引导以显示条件逻辑。 – Yuck

+4

@Yuck - 家庭作业重新发明轮子?呸! ;) –

回答

63

你可以简单地调用

using (StreamWriter w = File.AppendText("log.txt")) 

这将创建该文件,如果不存在,打开文件进行追加它。

编辑:

这足以:

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); 
    }     
}  

但如果你坚持先检查,你可以做这样的事情,但我不明白这一点。

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);      
    }     
} 

此外,有一点需要指出,你的代码是你正在做很多不必要的拆箱。如果您必须使用像ArrayList这样的普通(非通用)集合,请将对象取消装箱一次并使用引用。

然而,我perfer使用List<>为我的集合:

public class EmployeeList : List<Employee> 
6

是的,你需要否定File.Exists(path)如果你想检查文件是否存在。

12

或:

using(var fileStream = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) 
{ 
    using (StreamWriter sw = new StreamWriter(path, true)) 
    { 
     //... 
    } 
} 
-1

对于实施例

string rootPath = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System)); 
     rootPath += "MTN"; 
     if (!(File.Exists(rootPath))) 
     { 
      File.CreateText(rootPath); 
     } 
相关问题