VB.NET - "无法访问已关闭的文件"当试图读取文件的内容时

时间:2014-04-07 21:26:14

标签: vb.net visual-studio

以下是我的表格代码......

我正在尝试读取文件的内容,以便能够以数据库的形式存储为blob

    Try
        Dim fs = New FileStream(TextBox1.Text, FileMode.Open, FileAccess.Read)
        Dim rawData = New Byte(fs.Length) {}
        fs.Read(rawData, 0, fs.Length)
        fs.Close()

        ' Get File size
        Dim filesize As Long = fs.Length

        ' Get Extension
        Dim extension As String = Path.GetExtension(TextBox1.Text)

        'SQL query
        Dim cmdText = "INSERT INTO files VALUES (file_id, @fname, @content, @size, @ext, @comments, @vers, @auth);"

        'commit SQL query with connection statement
        Dim com As New MySqlCommand(cmdText, con)

        'place fields into parameters for the query
        com.Parameters.AddWithValue("@fname", filename.Text)
        com.Parameters.AddWithValue("@content", rawData)
        com.Parameters.AddWithValue("@size", filesize)
        com.Parameters.AddWithValue("@ext", extension)
        com.Parameters.AddWithValue("@comments", comments.Text)
        com.Parameters.AddWithValue("@vers", version.Text)
        com.Parameters.AddWithValue("@auth", home.userid.Text)

        'this will commit the record to the DB
        con.Close()
        con.Open()
        com.ExecuteNonQuery()
        con.Close()

    Catch ex As Exception

        MsgBox(ex.Message)

    End Try

1 个答案:

答案 0 :(得分:2)

如下面的链接所示,如果文件关闭或关闭,则Length属性可以抛出IOException http://msdn.microsoft.com/en-us/library/system.io.filestream.length.aspx

关闭文件后,您正在访问该长度。只需按下图所示翻转它们

  ' Get File size
   Dim filesize As Long = fs.Length
   fs.Close()