怎样在数据库里存去一个指定的文件?
首先在数据库里建立一个表,存放文件的字段为Image类型。
存入数据库的代码:
存入数据库的代码:
private void SaveDocument()
{
SqlConnection cn = new SqlConnection(@"Data Source=STAR2\RIVER3;Initial Catalog=Northwind;Integrated Security=True");
FileInfo fi = new FileInfo(@"C:\200801110040004.xml");
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;
cn.Open();
cm.CommandText = "insert into FileTable ( FileStr) values(@file)";
SqlParameter spFile = new SqlParameter("@file", SqlDbType.Image);
spFile.Value = bytes;
cm.Parameters.Add(spFile);
cm.ExecuteNonQuery();
cn.Close();
}
从数据库里读文件的代码:{
SqlConnection cn = new SqlConnection(@"Data Source=STAR2\RIVER3;Initial Catalog=Northwind;Integrated Security=True");
FileInfo fi = new FileInfo(@"C:\200801110040004.xml");
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;
cn.Open();
cm.CommandText = "insert into FileTable ( FileStr) values(@file)";
SqlParameter spFile = new SqlParameter("@file", SqlDbType.Image);
spFile.Value = bytes;
cm.Parameters.Add(spFile);
cm.ExecuteNonQuery();
cn.Close();
}
private void GetDocument()
{
SqlConnection cn = new SqlConnection(@"Data Source=STAR2\RIVER3;Initial Catalog=Northwind;Integrated Security=True");
SqlDataReader dr = null;
SqlCommand cm = new SqlCommand();
cm.Connection = cn;
cm.CommandType = CommandType.Text;
cm.CommandText = "select FileStr from FileTable where ID=1";
cn.Open();
dr = cm.ExecuteReader();
byte[] File = null;
if (dr.Read())
{
File = (byte[])dr[0];
}
cn.Close();
FileStream fs;
FileInfo fi = new System.IO.FileInfo(@"c:\myfile.txt");
fs = fi.OpenWrite();
fs.Write(File, 0, File.Length);
fs.Close();
}
{
SqlConnection cn = new SqlConnection(@"Data Source=STAR2\RIVER3;Initial Catalog=Northwind;Integrated Security=True");
SqlDataReader dr = null;
SqlCommand cm = new SqlCommand();
cm.Connection = cn;
cm.CommandType = CommandType.Text;
cm.CommandText = "select FileStr from FileTable where ID=1";
cn.Open();
dr = cm.ExecuteReader();
byte[] File = null;
if (dr.Read())
{
File = (byte[])dr[0];
}
cn.Close();
FileStream fs;
FileInfo fi = new System.IO.FileInfo(@"c:\myfile.txt");
fs = fi.OpenWrite();
fs.Write(File, 0, File.Length);
fs.Close();
}