重载文件函数VB.NET



我正试图通过ASP前端创建一个onclick函数来检查文件是否存在,如果不存在,请创建它并向其写入文本框文本,目前在下面的代码中收到一个错误,说我不能重载文件函数,有更好的方法吗?

更新问题是,当试图写入文件时,该文件仍然处于打开状态,从而引发错误。

请参阅以下代码:

Protected Sub Create_Click(sender As Object, e As EventArgs)
    Dim txtFile As String = "E:DocumentsVisual Studio 2013ProjectsSomeProjectTemplates" & FileName.Text & ".txt"
    If File.Exists(txtFile) Then
        Response.Write("A file of that name already exists.")
    Else
        File.Create(txtFile)
        File.WriteAllText(eTemplate.Text)
    End If
End Sub

我也试过:

    If File.Exists(txtFile) Then
        Response.Write("A file of that name already exists.")
    Else
        System.IO.File.Create(txtFile)
        Dim sw As New StreamWriter(txtFile, True)
        sw.Write(eTemplate.Text)
        sw.Close()
    End If

你说得对,因为它需要先关闭。

我先创建了一个文件流实例,创建了文件,关闭了它,然后写入它。把下面的代码放在你的代码中或写出来,但记住要更正文件路径。

   Protected Sub Create_Click(sender As Object, e As EventArgs)
    Dim txtFile As String = "E:wherever" & FileName.Text & ".txt"
    If System.IO.File.Exists(txtFile) Then
        Dim message As String = "A file by this name already exists, choose another or update the existing file."
    Else
        Dim fs As FileStream = File.Create(txtFile)
        fs.Close()
        Dim sw As New StreamWriter(txtFile, True)
        sw.Write(eTemplate.Text)
        sw.Close()
    End If
End Sub

最新更新