2012-04-30 39 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); 
     } 
相關問題