创建文本文件不起作用

时间:2016-06-23 12:39:29

标签: vb.net file

这可能是你们许多人已经看过几次的问题,但我真的很绝望,因为我在互联网上找到的每一个解决方案都无法正常工作。

我想创建一个简单的.txt文件。我的代码atm:

Public Class Form3
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If TextBox1.Text = "" Then
            MessageBox.Show("Your world needs a name")
        Else
            Dim file As System.IO.StreamWriter
            file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", True)
            file.WriteLine("Here is the first string.")
            file.Close()
        End If
    End Sub
End Class

正如您所看到的,按下按钮时和文本框中有文本时应创建一个文件。

程序无效或在错误的地方搜索文件?谢谢你的支持!

2 个答案:

答案 0 :(得分:0)

也可以使用这样的东西:

Public Class Form3
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If TextBox1.Text = "" Then
            MessageBox.Show("Your world needs a name")
        Else
            Using file As New StreamWriter("c:\test.txt", True)
                file.WriteLine("Here is the first string.")
                file.Close()
            End Using
        End If
    End Sub
End Class

答案 1 :(得分:-1)

试试此代码

Public Class Form3
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If TextBox1.Text = "" Then
        MessageBox.Show("Your world needs a name")
    Else
        Dim file As System.IO.StreamWriter
        file = My.Computer.FileSystem.OpenTextFileWriter(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "test.txt"), True)
        file.WriteLine("Here is the first string.")
        file.Close()
    End If
End Sub