视觉基本写入文件

时间:2016-02-06 14:43:01

标签: visual-studio streamwriter

当我想要用visual basic写入文件时,它说他不能说它已经在另一个procces中了但是没有其他的操作。 她是我的代码。

Imports System.IO

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Button1.Visible = False
        Label1.Visible = False
        pathlocation.Visible = True
        Button2.Visible = True
    End Sub

    Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        pathlocation.Visible = False
        Button2.Visible = False
    End Sub

    Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim path As String
        Dim modsl As String = "/modshop"
        Dim config As String = "/config"
        Dim configfile As String = "/config.txt"
        Dim configwriter As System.IO.StreamWriter
        path = pathlocation.Text
        path = path + modsl
        My.Computer.FileSystem.CreateDirectory(path)
        config = path + config
        My.Computer.FileSystem.CreateDirectory(config)
        configfile = config + configfile
        File.Create(configfile)
        configwriter = File.AppendText(configfile)
        configwriter.Write(path)
        configwriter.Close()
        Button2.Visible = False

    End Sub

    Private Sub pathlocation_TextChanged(sender As Object, e As EventArgs) Handles pathlocation.TextChanged

    End Sub
End Class

1 个答案:

答案 0 :(得分:1)

File.Create创建文件并返回FileStream,因此以下File.AppendText找到您自己已打开的文件并失败

考虑到这一点以及Directory.CreateDirectory方法在传递的路径中构建所有缺少的目录这一​​事实,您可以简化很多代码

Dim path = System.IO.Path.Combine(pathlocation.Text, "modshop")
Dim fullPath = System.IO.Path.Combine(path, "config")
Directory.CreateDirectory(fullPath)
Dim configFile = System.IO.Path.Combine(fullPath, "config.txt")
File.WriteAllText(configFile, path)

遵循代码的逻辑,我使用File.WriteAllText创建或覆盖configFile(如果存在)。如果要附加到现有文件而不覆盖其内容,请使用File.AppendAllText