source

VB의 txt 파일에 텍스트를 만들고 추가하는 중입니다.그물

nicesource 2023. 5. 9. 22:48
반응형

VB의 txt 파일에 텍스트를 만들고 추가하는 중입니다.그물

VB 사용.NET, 텍스트 파일이 없으면 만들고 텍스트 파일이 있으면 추가하려고 합니다.

어떤 이유로 텍스트 파일을 만드는 중인데 프로세스에서 파일에 액세스할없다는 오류가 발생합니다.

그리고 프로그램을 실행할 때 텍스트를 쓰는 것인데 어떻게 하면 새 줄에 쓸 수 있습니까?

Dim strFile As String = "C:\ErrorLog_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"

Dim sw As StreamWriter
Dim fs As FileStream = Nothing

If (Not File.Exists(strFile)) Then
    Try
        fs = File.Create(strFile)
        sw = File.AppendText(strFile)
        sw.WriteLine("Start Error Log for today")

    Catch ex As Exception
        MsgBox("Error Creating Log File")
    End Try
Else
    sw = File.AppendText(strFile)
    sw.WriteLine("Error Message in  Occured at-- " & DateTime.Now)

    sw.Close()
End If

사용해 보십시오.

Dim strFile As String = "yourfile.txt"
Dim fileExists As Boolean = File.Exists(strFile)
Using sw As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))
    sw.WriteLine( _
        IIf(fileExists, _
            "Error Message in  Occured at-- " & DateTime.Now, _
            "Start Error Log for today"))
End Using

확인 안 함File.Exists()이런 거죠.사실, 모든 것이 너무 복잡합니다.이렇게 하면 필요한 작업을 수행할 수 있습니다.

Dim strFile As String = $@"C:\ErrorLog_{DateTime.Today:dd-MMM-yyyy}.txt"
File.AppendAllText(strFile, $"Error Message in  Occured at-- {DateTime.Now}{Environment.NewLine}")

코드 두 줄로 모두 정리했습니다 :)

이것은 다른 답변처럼 프로그램 로직을 변경하지 않고도 작동합니다(각 파일의 맨 위에 "시작 오류"를 출력하지 않음). 예외 처리 코드를 추가해야 합니다.

Dim filePath As String = String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))

Dim fileExists As Boolean = File.Exists(filePath)

Using writer As New StreamWriter(filePath, True)
    If Not fileExists Then
        writer.WriteLine("Start Error Log for today")
    End If
    writer.WriteLine("Error Message in  Occured at-- " & DateTime.Now)
End Using

파일을 만든 후 파일을 닫지 않았으므로 파일에 쓸 때 사용자가 직접 파일을 사용하고 있습니다.Create 메서드는 파일을 열고 FileStream 개체를 반환합니다.FileStream을 사용하여 파일에 쓰거나 파일에 쓰기 전에 닫으십시오.이 경우 StreamWriter를 반환하므로 CreateText 메서드를 대신 사용하는 것이 좋습니다.

또한 파일이 없는 경우 StreamWriter를 닫는 것을 잊었기 때문에 다음 번에 파일에 쓰려고 할 때 StreamWriter가 잠겨 있을 가능성이 높습니다.그리고 파일이 존재하지 않는 경우 오류 메시지를 파일에 쓰는 것을 잊었습니다.

Dim strFile As String = "C:\ErrorLog_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"
Dim sw As StreamWriter
Try
   If (Not File.Exists(strFile)) Then
      sw = File.CreateText(strFile)
      sw.WriteLine("Start Error Log for today")
   Else
      sw = File.AppendText(strFile)
   End If
   sw.WriteLine("Error Message in  Occured at-- " & DateTime.Now)
   sw.Close()
Catch ex As IOException
   MsgBox("Error writing to log file.")
End Try

참고: 예외를 탐지할 때 기본 클래스 예외를 탐지하지 말고 관련된 예외만 탐지합니다.이 경우에는 IO Exception에서 상속받는 것이 됩니다.

다음과 같은 단순 통화(예외 처리가 추가됨)를 사용하는 것이 어떻습니까?

File.AppendAllText(strFile, "Start Error Log for today")


편집된 답변
이렇게 하면 질문에 완전히 답할 수 있습니다!

If File.Exists(strFile)
  File.AppendAllText(strFile, String.Format("Error Message in  Occured at-- {0:dd-MMM-yyyy}{1}", Date.Today, Environment.NewLine))
Else
  File.AppendAllText(strFile, "Start Error Log for today{0}Error Message in  Occured at-- {1:dd-MMM-yyyy}{0}", Environment.NewLine, Date.Today)
End If

이 스레드가 오래된 스레드라는 것을 알고 있는 동안 위의 if 블록이 다음을 사용하는 데 적합하지 않다는 것을 알게 되었습니다.

다음 사항이 수정되었습니다.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim filePath As String =
      String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))
    Using writer As New StreamWriter(filePath, True)
        If File.Exists(filePath) Then
            writer.WriteLine("Error Message in  Occured at-- " & DateTime.Now)
        Else
            writer.WriteLine("Start Error Log for today")
        End If
    End Using
End Sub

다음과 같은 방법으로 시도해 보십시오.

Dim filePath As String = 
  String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))

if File.Exists(filePath) then

Using writer As New StreamWriter(filePath, True)
writer.WriteLine("Error Message in  Occured at-- " & DateTime.Now)

Else
writer.WriteLine("Start Error Log for today")
End Using

end if

 If File.Exists(filePath) Then
        Using writer As New StreamWriter(filePath, True)
            writer.WriteLine(message & " - " & DateTime.Now)
        End Using
    Else
        Using writer As New StreamWriter(filePath, True)
            writer.WriteLine("SUSHI Bot Event LOG:  Started" & " - " & DateTime.Now)
        End Using
    End If

언급URL : https://stackoverflow.com/questions/1613666/creating-and-appending-text-to-txt-file-in-vb-net

반응형