上传文件并保存到数据库 [英] Upload File and Save to Database
本文介绍了上传文件并保存到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从磁盘上传文件,然后将文件插入varbinary db列中.
I am trying to upload a file from disk and then insert the file into a varbinary db column.
我似乎不知道如何插入二进制文件.
I can't seem to figure out how to insert the binary file.
我在WPF应用程序中使用C#和Linq到Sql.
I am using C# and Linq to Sql in a WPF application.
这是我到目前为止正在尝试的!任何建议或意见将不胜感激.
Here is what I am trying so far! Any suggestions or advice would be appreciated.
private void UploadFile()
{
DatabaseData.DataClassesDataContext context = new DatabaseData.DataClassesDataContext();
{
OpenFileDialog dlgOpen = new OpenFileDialog();
dlgOpen.Title = "Select file";
FileData fd = new FileData();
if (dlgOpen.ShowDialog() ?? false)
{
FileStream inStream = File.OpenRead(dlgOpen.FileName);
//FileStream outStream = File.OpenWrite(dlgOpen.FileName + ".xlsx");
int b;
while ((b = inStream.ReadByte()) > -1)
// outStream.WriteByte((byte)b);
fd.FileId = Guid.NewGuid();
//fd.DataFile = inStream;//DataFile is the Varbinary column in the db
fd.Title = dlgOpen.FileName;
fd.FileExtension = txtExtension.text;
context.FileDatas.InsertOnSubmit(fd);
context.SubmitChanges();
//outStream.Flush();
//outStream.Close();
inStream.Close();
}
}
}
推荐答案
不确定是否可行,请尝试
Not sure if this will work, but try this
if (dlgOpen.ShowDialog() ?? false)
{
byte[] bytes = System.IO.File.ReadAllBytes(dlgOpen.FileName);
fd.FileId = Guid.NewGuid();
fd.DataFile = bytes;
fd.Title = dlgOpen.FileName;
context.FileDatas.InsertOnSubmit(fd);
context.SubmitChanges();
这篇关于上传文件并保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文