您的位置:首页 > 数据库

文件以二进制存入数据库和从数据库读取二进制文件

2013-08-06 10:15 357 查看
if (FileUpload1.FileContent != null){int len = (int)FileUpload1.FileContent.Length;string path = Server.MapPath("~/test/xx.docx");//"@d:\\xx.docx";FileUpload1.SaveAs( path);FileStream fs = new FileStream(path,FileMode.Open,FileAccess.Read);BinaryReader br = new BinaryReader(fs);                  FileByteEx = br.ReadBytes(len);            /*如果长度大于int类型的最大长度时可以考虑分段进行读取            while(redLen<total){            buffer = new byte[size];            buffer=br.ReadBytes(size);            redLen += size;            }  */fs.Close();         br.Close();        //注只是写个大概的意思,下边创建数据库连接什么的都没有具体写。         SqlCommand  cmd=new Sqlcommand();        string sql="insert into test([file]) values (@file)";SqlParameter par= new SqlParameter("@file", SqlDbType.VarBinary);        cmd.SqlParameter=par;            SqlCommand cmd = new SqlCommand();        cmd.Connection = new SqlConnection(strCon);        cmd.CommandType = SqlDataSourceCommandType.Text;        cmd.CommandText = sql;// 数据库字段设置为  varbinary(MAX)         }
从数据库取出
和普通取数据一样放在dataset中,然后从dataset中取出(转换成byte数组)FILE_CONTENT_B=(byte[])ds.Tables[0].Rows[0]["FILE_CONTENT_B"];通过下面的语句直接打开
var filebyte = modSysFiles.FILE_CONTENT_B;//创建的文件路径string path = Server.MapPath("~/test/xx.docx"); //@"D:\test\data\" + "xxx.docx";//按照路径实例化文件var file = new FileStream(path, FileMode.Create, FileAccess.Write);//实例化一个用于写的 BinaryWritervar bw = new BinaryWriter(file);//var bwr  = new BinaryReader//将传进来的二进制字符转换为8位无符号整数数组再写进去bw.Write(filebyte);bw.Close();//关闭二进制流写入器file.Close();  //关闭文件流//创建Process命令var cmd = new System.Diagnostics.Process();//创建要运行的文件或者程序var startfile = new System.Diagnostics.ProcessStartInfo{FileName = file.Name,//文件完全路径WindowStyle = ProcessWindowStyle.Normal,//Windows窗口样式UseShellExecute = true//为true,则用默认的打开方式打开,如果是exe等,设置为false};cmd.StartInfo = startfile;cmd.Start(); //打开文件

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: