我尝试从gridview下载文件。。我在数据库中保存文件,然后在网格视图中显示我尝试这个
我将文件保存在数据库表中,而不是文件夹中,所以我尝试下载文件
当我这样做的时候,文档是下载的,但当我调试代码并在这行检查时出现了问题Dim行=db_stu.dResult.Tables(0).Rows(i)dResult显示
docid document docname docextension
1014 System.Byte[] Book2.xlsx .xlsx
然后当我进一步进行时,docname显示"1912218726836.xlsx"这一点,以及文件下载为损坏的
这两行加在一起是错误的:
Dim binary() As Byte = TryCast(structDb.dstResult.Tables(0).Rows(i).Item("document"), Byte())
Dim ms As MemoryStream = New MemoryStream(binary)
使用TryCast的原因是,您尝试强制转换的对象可能不是您尝试将其强制转换为的类型。在这种情况下,TryCast
将返回Nothing
。使用TryCast
后应始终进行Nothing
测试,但您尚未进行测试。您使用的结果就好像您确信会有一个该类型的对象一样。如果您知道这一点,那么您应该使用DirectCast
而不是TryCast
。
即使您知道引用不会指向不同类型的对象,并且您使用DirectCast
,如果您强制转换空引用,即Nothing
,那么您仍然会得到Nothing
。因此,您首先需要确定structDb.dstResult.Tables(0).Rows(i).Item("document")
是否可以引用Byte()
以外类型的对象。如果不能,则使用DirectCast
而不是TryCast
。无论哪种方式,该表达式似乎都可以产生Nothing
,因此您需要检查Nothing
,例如
Dim binary() As Byte = TryCast(structDb.dstResult.Tables(0).Rows(i).Item("document"), Byte())
If binary IsNot Nothing Then
Dim ms As MemoryStream = New MemoryStream(binary)
'...
End If
编辑:如果列是可以为null的,那么您需要首先测试行是否包含null,然后只在有空的情况下使用数据:
Dim row = structDb.dstResult.Tables(0).Rows(i)
If Not row.IsNull("document") Then
'There is data so go ahead and use it.
Dim binary = DirectCast(row("document"), Byte())
'...