将文本写入.txt文件的通用代码?

时间:2019-04-19 04:11:43

标签: vb.net

我有一些当前将文本写入.txt文件的代码,但是在另一台计算机上进行了测试,用户必须更改代码行"C:\Users\Blake\Documents\test2.txt"并创建/保存名为test2的.txt文件。我希望我的代码保持不变,因为它确实起作用。任何建议表示赞赏。

    Dim FILE_NAME As String = "C:\Users\owner\Documents\test2.txt" 'Sends information to test2.txt 
            If System.IO.File.Exists(FILE_NAME) = True Then
                Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
                'File.WriteLine("wILDO THE ")
                objWriter.Write("Aircraft Make & Model: " & TextBox4.Text & ", N-number: " & TextBox3.Text)
                objWriter.Write("
Gascolator Removed & Inspected in accordance with FAA approved maintenance manual")
                objWriter.Write("

Signature _____________________________")
                objWriter.Write(" " & DateTime.Now)
                'Displays current date And time
                objWriter.Close()

                MsgBox("Log Book Entry Created")
            Else
                MsgBox("File Does Not Exist")
        End If
        Else
        ErrorProvider1.SetError(Button2, "All boxes must be checked")
        End If

    End Sub

End Class

2 个答案:

答案 0 :(得分:0)

文档路径在SpecialDirectories类中可用。您可以简单地做到这一点:

Dim FILE_NAME As String =  My.Computer.FileSystem.SpecialDirectories.MyDocuments + "\test2.txt"

答案 1 :(得分:0)

尝试使用此:

 Dim FILE_NAME As String =  IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments,"test2.txt")