반응형
파일이없는 경우 파일 만들기
파일이없는 경우 코드를 읽어야합니다. 지금은 존재하는 경우 읽고 추가하고 있습니다. 다음은 코드입니다.
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
반응형
'Program Tip' 카테고리의 다른 글
변수에서 대소 문자 구분을 무시하는 Windows 배치 명령 (0) | 2020.11.17 |
---|---|
Blob에 저장된 미디어 파일의 콘텐츠 유형 설정 (0) | 2020.11.17 |
최적의 scrypt 작업 요소는 무엇입니까? (0) | 2020.11.17 |
stdout을 변수로 캡처하지만 여전히 콘솔에 표시 (0) | 2020.11.17 |
lodash.each가 native forEach보다 빠른 이유는 무엇입니까? (0) | 2020.11.17 |