【发布时间】:2012-04-25 16:11:04
【问题描述】:
我真的在为此苦苦挣扎,任何帮助将不胜感激。
我需要一些代码来遍历文件夹中的每个文件并将其保存到数据库中,以便以后可以将其拉出并显示。我还没到显示部分,哈哈,还在尝试获取数据库中的文件。
到目前为止,我遇到了一个错误
Value of type '1-dimensional array of Byte' cannot be converted to 'String'.
数据库中的所有字段都是nvarchar(MAX)
Dim dir As New System.IO.DirectoryInfo("C:\Users\Will\Desktop\SUBARU")
For Each f As System.IO.FileInfo In dir.GetFiles("*.*")
Using db As New FileStoreAppDBEntities
Dim NewFile As New StoredFile
NewFile.FileName = f.Name
NewFile.FileSize = f.Length
'got trouble here
Dim ImageData As Byte() = System.IO.File.ReadAllBytes(f.FullName)
NewFile.FileContent = ImageData
'
NewFile.FileType = f.Extension
db.StoredFiles.AddObject(NewFile)
db.SaveChanges()
End Using
Next
也许我做错了?
非常感谢您的帮助。
--编辑
这似乎做到了!
For Each f As System.IO.FileInfo In dir.GetFiles("*.*")
Using db As New FileStoreAppDBEntities
Dim NewFile As New StoredFile
NewFile.FileName = f.Name
NewFile.FileSize = f.Length
Dim filename As String = f.FullName
NewFile.FileContent = System.IO.File.ReadAllBytes(filename)
NewFile.FileType = f.Extension.ToLower
db.StoredFiles.AddObject(NewFile)
db.SaveChanges()
End Using
Next
虽然不确定性能,但我认为这可能会将文件放入内存中然后发送而不是流式传输?
然后检索文件:
Using db As New FileStoreAppDBEntities
Dim IDofFile As Integer = 31
Dim getFile = (From files In db.StoredFiles Where files.FileID = IDofFile Select files).SingleOrDefault
'getFile.FileName eg. mydocument.txt
System.IO.File.WriteAllBytes("C:\LocationToSaveTo\" & getFile.FileName, getFile.FileContent)
End Using
对于非常大的文件出现错误System.OutOfMemoryException
不过,对于较小的文件也能完美运行...
也许可以将文件分块?
【问题讨论】:
-
您确实应该使用 FILESTREAM 数据类型(假设这是 sql server)。 EF 不是执行此操作的工具:stackoverflow.com/questions/10055280/….
标签: winforms entity-framework-4 vb.net-2010