2024年4月11日发(作者:)
C# 文件保存到数据库中或者从数据库中读取文件
其实,方法非常的简单,只是可能由于这些朋友刚刚开始编程不久,一时没有找到方法而已。
下面介绍一下使用C#来完成此项任务。
首先,介绍一下保存文件到数据库中。
将文件保存到数据库中,实际上是将文件转换成二进制流后,将二进制流保存到数据库相应
的字段中。在SQL Server中该字段的数据类型是Image,在Access中该字段的数据类型是
OLE对象。
复制代码 代码如下:
//保存文件到SQL Server数据库中
FileInfo fi=new FileInfo(fileName);
FileStream fs=ad();
byte[] bytes=new byte[];
(bytes,0,32());
SqlCommand cm=new SqlCommand();
tion=cn;
dType=;
if(==0) ();
dText="insert into "+tableName+"("+fieldName+") values(@file)";
SqlParameter spFile=new SqlParameter("@file",);
=bytes;
(spFile);
eNonQuery()
//保存文件到Access数据库中
FileInfo fi=new FileInfo(fileName);
FileStream fs=ad();
byte[] bytes=new byte[];
(bytes,0,32());
OleDbCommand cm=new OleDbCommand();
tion=cn;
dType=;
if(==0) ();
dText="insert into "+tableName+"("+fieldName+") values(@file)";
OleDbParameter spFile=new OleDbParameter("@file",);
=bytes;
(spFile);
eNonQuery()
//保存客户端文件到数据库
sql="update t_mail set attachfilename=@attachfilename,attachfile=@attachfile
mailid="+mailid;
myCommand = new SqlCommand(sql, new SqlConnection(ConnStr));
where
string path = fl_me;
string filename=ing(dexOf("")+1,dexOf("")-1);
("@attachfilename",r);
ters["@attachfilename"].Value=filename;
("@attachfile",);
Stream fileStream = fl_tream;
int intFileSize = fl_tLength;
byte[] fileContent = new byte[intFileSize];
int intStatus = (fileContent,0,intFileSize); //文件读取到fileContent数组中
ters["@attachfile"].Value=((byte[])fileContent);
();
();
eNonQuery();
();
代码中的fileName是文件的完整名称,tableName是要操作的表名称,fieldName是要保存
文件的字段名称。
两段代码实际上是一样的,只是操作的数据库不同,使用的对象不同而已。
接着,在说说将文件从数据库中读取出来,只介绍从SQL Server中读取。
复制代码 代码如下:
SqlDataReader dr=null;
SqlConnection objCn=new SqlConnection();
tionString="Data Source=(local);User ID=sa;Password=;Initial Catalog=Test";
SqlCommand cm=new SqlCommand();
tion=cn;
dType=;
dText="select "+fieldName+" from "+tableName+" where ID=1";
dr=eReader();
byte[] File=null;
if(())
{
File=(byte[])dr[0];
}
FileStream fs;
FileInfo fi=new fo(fileName);
fs=ite();
(File,0,);
();
上面的代码是将保存在数据库中的文件读取出来并保存文fileName指定的文件中。
在使用上面的代码时,别忘了添加ent和引用。
修改:
将读文件的下面部分的代码
复制代码 代码如下:


发布评论