//保存文件到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()
//保存客户端文件到数据库
      sql="update t_mail set attachfilename=@attachfilename,attachfile=@attachfile where mail].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是文件的完整名称,tableName是要操作的表名称,fieldName是要保存文件的字段名称。
从数据库中读取出来,只介绍从SQL Server中读取。

 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();
 
上面的代码是将保存在数据库中的文件读取出来并保存在fileName指定的文件中。
 
在使用上面的代码时,别忘了添加System.Data.SqlClient和System.IO引用。

相关文章:

  • 2021-12-04
  • 2022-12-23
  • 2021-11-20
  • 2021-09-16
  • 2021-11-13
  • 2021-11-23
  • 2022-02-19
猜你喜欢
  • 2021-09-22
  • 2021-11-04
  • 2022-02-26
  • 2021-09-07
  • 2021-11-04
相关资源
相似解决方案