Program Tip

파일이없는 경우 파일 만들기

programtip 2020. 11. 17. 21:00
반응형

파일이없는 경우 파일 만들기


파일이없는 경우 코드를 읽어야합니다. 지금은 존재하는 경우 읽고 추가하고 있습니다. 다음은 코드입니다.

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

}


당신은 단순히 전화 할 수 있습니다

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

또한 코드에서 지적해야 할 한 가지는 불필요한 unboxing을 많이 수행하고 있다는 것입니다. 와 같은 일반 (비 제네릭) 컬렉션을 사용해야하는 ArrayList경우 개체를 한 번 풀고 참조를 사용합니다.

그러나 List<>내 컬렉션에는 다음 을 사용 하는 것이 좋습니다 .

public class EmployeeList : List<Employee>

또는:

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

수동으로 확인할 필요도 없습니다. File.Open이 자동으로 수행합니다. 시험:

using (StreamWriter sw = new StreamWriter(File.Open(path, System.IO.FileMode.Append))) 
{

Ref: http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx


Yes, you need to negate File.Exists(path) if you want to check if the file doesn't exist.


For Example

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

참고URL : https://stackoverflow.com/questions/10383053/create-file-if-file-does-not-exist

반응형