简体   繁体   中英

Overload File Function VB.NET

I am trying to create an onclick function through ASP front end to check if a file exists, if not create it and write textbox text to it, currently getting an error on the below code saying that I cannot overload the file function, is there a better way of doing this?

UPDATE The issue is the file is still open when trying to write to it which is throwing the error.

Please see below code:

Protected Sub Create_Click(sender As Object, e As EventArgs)
    Dim txtFile As String = "E:Documents\Visual Studio 2013\Projects\SomeProject\Templates\" & 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

I have also tried:

    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

You're right on the money, it is because it needs to be closed first.

I created a file stream instance first, created the file, closed it and then wrote to it. Put the below code in yours or write it out, but remember to correct the file path.

   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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM