我试图通过ASP前端创建一个onclick函数来检查文件是否存在,如果没有创建它并向其写入文本框文本,当前在下面的代码中出现错误,说我不能重载文件函数,有更好的方法吗?
更新 问题是文件在尝试写入时仍处于打开状态,这会导致错误。
请参阅以下代码:
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
我也尝试过:
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
答案 0 :(得分:1)
你是对的,这是因为它需要先关闭。
我首先创建了一个文件流实例,创建了文件,关闭它然后写入它。将以下代码放入您的代码或写出来,但请记住纠正文件路径。
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