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

问题描述 投票:-2回答:2

我的代码目前将文本写入.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
vb.net
2个回答
0
投票

试试这个:

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

0
投票

文档路径在SpecialDirectories类中可用。你可以这样做:

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