IT

존재하지 않고 새 줄을 추가하는 경우 .txt 파일을 만듭니다.

lottoking 2020. 6. 15. 08:02
반응형

존재하지 않고 새 줄을 추가하는 경우 .txt 파일을 만듭니다.


.txt 파일을 만들어서 쓰고 싶습니다. 파일이 이미 존재하면 더 많은 줄을 추가하고 싶습니다.

string path = @"E:\AppServ\Example.txt";
if (!File.Exists(path))
{
    File.Create(path);
    TextWriter tw = new StreamWriter(path);
    tw.WriteLine("The very first line!");
    tw.Close();
}
else if (File.Exists(path))
{
    TextWriter tw = new StreamWriter(path);
    tw.WriteLine("The next line!");
    tw.Close(); 
}

그러나 첫 번째 줄은 항상 덮어 쓰는 것 같습니다 ... 같은 줄에 쓰지 않으려면 어떻게해야합니까 (루프에서 이것을 사용하고 있습니까)?

나는 그것이 매우 간단한 일이라는 것을 알고 있지만 WriteLine이전 에는 방법을 사용하지 않았습니다 . 저는 C #을 처음 접했습니다.


올바른 생성자를 사용하십시오 .

else if (File.Exists(path))
{
    using(var tw = new StreamWriter(path, true))
    {
        tw.WriteLine("The next line!");
    }
}

string path = @"E:\AppServ\Example.txt";
File.AppendAllLines(path, new [] { "The very first line!" });

File.AppendAllText ()도 참조하십시오. AppendAllLines는 줄을 직접 넣지 않아도 각 줄에 개행을 추가합니다.

두 가지 방법 모두 파일이 존재하지 않으면 파일을 작성하므로 필요하지 않습니다.


string path=@"E:\AppServ\Example.txt";

if(!File.Exists(path))
{
   File.Create(path).Dispose();

   using( TextWriter tw = new StreamWriter(path))
   {
      tw.WriteLine("The very first line!");
   }

}    
else if (File.Exists(path))
{
   using(TextWriter tw = new StreamWriter(path))
   {
      tw.WriteLine("The next line!");
   }
}


StreamWriter가 자동으로 파일을 존재하기 때문에 실제로 파일이 있는지 확인할 필요는 없습니다. 추가 모드에서 파일을 열면 파일이 존재하지 않으면 파일이 만들어지며 항상 추가하고 덮어 쓰지 않습니다. 따라서 초기 점검은 중복됩니다.

TextWriter tw = new StreamWriter(path, true);
tw.WriteLine("The next line!");
tw.Close(); 

File.AppendAllText는 파일에 문자열을 추가합니다. 파일이 없으면 텍스트 파일도 작성합니다. 내용을 읽을 필요가 없으면 매우 효율적입니다. 유스 케이스가 로깅 중입니다.

File.AppendAllText("C:\\log.txt", "hello world\n");

"추가"모드에서 파일을 열기 만하면됩니다.

http://msdn.microsoft.com/en-us/library/3zc0w663.aspx


StreamWriter를 시작하면 이전에 있던 텍스트보다 우선합니다. 다음과 같이 append 속성을 사용할 수 있습니다.

TextWriter t = new StreamWriter(path, true);

 else if (File.Exists(path)) 
{ 
  using (StreamWriter w = File.AppendText(path))
        {
            w.WriteLine("The next line!"); 
            w.Close();
        }
 } 

FileStream을 사용할 수 있습니다. 이것은 당신을 위해 모든 작업을 수행합니다.

http://www.csharp-examples.net/filestream-open-file/


From microsoft documentation, you can create file if not exist and append to it in a single call File.AppendAllText Method (String, String)

.NET Framework (current version) Other Versions

Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file. Namespace: System.IO Assembly: mscorlib (in mscorlib.dll)

Syntax C#C++F#VB public static void AppendAllText( string path, string contents ) Parameters path Type: System.String The file to append the specified string to. contents Type: System.String The string to append to the file.

AppendAllText


using(var tw = new StreamWriter(path, File.Exists(path)))
{
    tw.WriteLine(message);
}

Try this.

string path = @"E:\AppServ\Example.txt";
if (!File.Exists(path))
{
    using (var txtFile = File.AppendText(path))
    {
        txtFile.WriteLine("The very first line!");
    }
}
else if (File.Exists(path))
{     
    using (var txtFile = File.AppendText(path))
    {
        txtFile.WriteLine("The next line!");
    }
}

You can just use File.AppendAllText() Method this will solve your problem. This method will take care of File Creation if not available, opening and closing the file.

var outputPath = @"E:\Example.txt";
var data = "Example Data";
File.AppendAllText(outputPath, data);

참고URL : https://stackoverflow.com/questions/9907682/create-a-txt-file-if-doesnt-exist-and-if-it-does-append-a-new-line

반응형