2012-04-30 3 views
37

파일이 없으면 코드를 읽어야 다른 파일을 만들 수 있습니다. 지금 그것이 존재한다면 그것은 독서이며, 창조하고 덧붙입니다. 코드는 다음과 같습니다.파일이없는 경우 파일 만들기

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/ko-kr/library/ms143356.aspx) -이 코드는 한 줄의 코드에서만 필요합니다. –

+0

@ShadowWizard 이후 th 숙제 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과 같은 일반 (일반이 아닌) 콜렉션을 사용해야하는 경우, 오브젝트를 한 번 unbox하고 참조를 사용하십시오.

그러나, 나는 내 컬렉션에 대한 List<>를 사용하는 perfer :

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); 
     } 
관련 문제