简体   繁体   English

重载文件功能VB.NET

[英]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? 我正在尝试通过ASP前端创建一个onclick函数,以检查文件是否存在,如果不创建文件并向其写入文本框文本,当前在以下代码上显示错误,提示我无法重载文件功能,是否存在更好的方法吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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