如何将文本文件写入vb.net中的桌面子文件夹

时间:2015-04-15 01:05:41

标签: vb.net

我想写一个文本文件到我在桌面上的文件夹中创建的子文件夹,即

桌面文件夹>子文件夹>文本文件

我想出的代码如下所示。我在父桌面文件夹中创建了子文件夹,但无法找到此子文件夹来编写和保存文本文件。请相信任何建议。我正在使用Visual Basic 2010 Express。提前谢谢。



Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

‘Check if a sub-folder with the title specified in Textbox1 does not exist in desktop folder      titled Family

        If (Not System.IO.Directory.Exists("C:\Users\" & Environ("username") & "\Desktop\Family\" & TextBox1.Text)) Then

  	‘Create a sub-folder within desktop folder titled Family with the title specified in Textbox1

         System.IO.Directory.CreateDirectory("C:\Users\" & Environ("username") & "\Desktop\Family\" & TextBox1.Text)
        End If

Dim fileTXT As New IO.StreamWriter("C:\Users\" & Environ("username") & "\Desktop\Family\" & TextBox1.Text & TextBox1.Text & ".TXT")

        fileTXT.Write(TextBox2.Text)
        fileTXT.WriteLine("")
        Close()

    End Sub




2 个答案:

答案 0 :(得分:2)

我会这样写你的代码:

    Dim di = New DirectoryInfo(Path.Combine( _
            Environment.GetFolderPath(Environment.SpecialFolder.Desktop), _
            "Family\" & TextBox1.Text))
    If Not di.Exists
        di.Create()
    End If
    Dim fn = Path.Combine(di.FullName, TextBox1.Text + ".TXT")
    File.WriteAllText(fn, TextBox2.Text + Environment.NewLine)

答案 1 :(得分:1)

尝试此操作以获取桌面文件夹:

Environment.GetFolderPath(Environment.SpecialFolder.Desktop)

然后,您可以使用System.IO.Path.Combine添加Family子文件夹。在创建子文件夹之前确保子文件夹存在。