C#数据库读写文件

//保存文件到SQL Server数据库中 
FileInfo fi=new FileInfo(fileName); 
FileStream fs=fi.OpenRead(); 
byte[] bytes=new byte[fs.Length]; 
fs.Read(bytes,0,Convert.ToInt32(fs.Length)); 
SqlCommand cm=new SqlCommand(); 
cm.Connection=cn; 
cm.CommandType=CommandType.Text; 
if(cn.State==0) cn.Open(); 
cm.CommandText="insert into "+tableName+"("+fieldName+") values(@file)"; 
SqlParameter spFile=new SqlParameter("@file",SqlDbType.Image); 
spFile.Value=bytes; 
cm.Parameters.Add(spFile); 
cm.ExecuteNonQuery() 
//保存文件到Access数据库中 
FileInfo fi=new FileInfo(fileName); 
FileStream fs=fi.OpenRead(); 
byte[] bytes=new byte[fs.Length]; 
fs.Read(bytes,0,Convert.ToInt32(fs.Length)); 
OleDbCommand cm=new OleDbCommand(); 
cm.Connection=cn; 
cm.CommandType=CommandType.Text; 
if(cn.State==0) cn.Open(); 
cm.CommandText="insert into "+tableName+"("+fieldName+") values(@file)"; 
OleDbParameter spFile=new OleDbParameter("@file",OleDbType.Binary); 
spFile.Value=bytes; 
cm.Parameters.Add(spFile); 
cm.ExecuteNonQuery() 
//保存客户端文件到数据库 
sql="update t_mail set attachfilename=@attachfilename,attachfile=@attachfile where mailid="+mailid; 
myCommand = new SqlCommand(sql, new SqlConnection(ConnStr)); 
string path = fl_name.PostedFile.FileName; 
string filename=path.Substring(path.LastIndexOf("\")+1,path.Length-path.LastIndexOf("\")-1); 
myCommand.Parameters.Add("@attachfilename",SqlDbType.VarChar); 
myCommand.Parameters["@attachfilename"].Value=filename; 
myCommand.Parameters.Add("@attachfile",SqlDbType.Image); 
Stream fileStream = fl_name.PostedFile.InputStream; 
int intFileSize = fl_name.PostedFile.ContentLength; 
byte[] fileContent = new byte[intFileSize]; 
int intStatus = fileStream.Read(fileContent,0,intFileSize); //文件读取到fileContent数组中 
myCommand.Parameters["@attachfile"].Value=((byte[])fileContent); 
fileStream.Close(); 
myCommand.Connection.Open(); 
myCommand.ExecuteNonQuery(); 

myCommand.Connection.Close(); 


将保存在数据库中的文件读取出来并保存文fileName指定的文件

SqlDataReader dr=null; 
SqlConnection objCn=new SqlConnection(); 
objCn.ConnectionString="Data Source=(local);User ID=sa;Password=;Initial Catalog=Test"; 
SqlCommand cm=new SqlCommand(); 
cm.Connection=cn; 
cm.CommandType=CommandType.Text; 
cm.CommandText="select "+fieldName+" from "+tableName+" where ID=1"; 
dr=cm.ExecuteReader(); 
byte[] File=null; 
if(dr.Read()) 

File=(byte[])dr[0]; 

FileStream fs; 
FileInfo fi=new System.IO.FileInfo(fileName); 
fs=fi.OpenWrite(); 
fs.Write(File,0,File.Length); 
fs.Close(); 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值