VB.NET - 尝试将文件写入驱动器时出现UnauthorizedAccessException

时间:2014-02-07 10:02:30

标签: wpf vb.net file windows-8 unauthorizedaccessexcepti

我正在按照其他post中描述的方法来存储和检索MSSQL 2008数据库中的任何文件。一切正常,除非我尝试将文件保存到磁盘上的任何位置,我得到UnauthorizedAccessException。以下是迄今为止所做的事情

  1. 将路径硬编码为“C:\ Temp”和“D:\” - UnauthorizedAccessException
  2. 尝试以管理员身份运行build .exe - 程序意外关闭
  3. 有人能指出我正确的方向解决这个问题吗?

    我在Windows 8上,这是我正在使用的代码;

    Public Sub downloadLearningObject(learningObjectID As Integer, folderPath As String) Implements ILearningObjectDAO.downloadLearningObject
        Dim connection As String = DatabaseConnection.ConnectionString
        Using con As New SqlConnection(connection)
            con.Open()
            Dim selectQuery As String = "SELECT File From LearningObject WHERE LearningObjectID=" & learningObjectID
    
            Dim cmd As New SqlCommand(selectQuery, con)
            Using sqlQueryResult = cmd.ExecuteReader()
                If sqlQueryResult IsNot Nothing Then
                    sqlQueryResult.Read()
                    Dim blob = New [Byte]((sqlQueryResult.GetBytes(0, 0, Nothing, 0, Integer.MaxValue)) - 1) {}
                    sqlQueryResult.GetBytes(0, 0, blob, 0, blob.Length)
    
                    'the following line is producing the exception
                    Using fs = New FileStream(folderPath, FileMode.OpenOrCreate, FileAccess.ReadWrite) 
                        fs.Write(blob, 0, blob.Length)
                    End Using
                End If
            End Using
    
        End Using
    End Sub
    

1 个答案:

答案 0 :(得分:0)

我发现我的"路径"的格式化字符串是错误的。它必须是" C:\ Temp \"而不是" C:\ Temp"。字符串末尾缺少反斜杠触发了异常。