/// <summary>
/// 保存文件到数据库
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
string conn = @"Data Source=YANGYIBANG\SQLEXPRESS;Initial Catalog=joe;Integrated Security=True";
SqlConnection cn = new SqlConnection(conn);
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
//openFileDialog1.InitialDirectory = "c:\\";
//openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
//openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
FileInfo fi = new FileInfo(openFileDialog1.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 title (titileName, files ) values('aaa',@file)";
SqlParameter spFile = new SqlParameter("@file", SqlDbType.Image);
spFile.Value = bytes;
cm.Parameters.Add(spFile);
cm.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
/// <summary>
/// 从数据库就读取文件另存为
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
try
{
string conn = @"Data Source=YANGYIBANG\SQLEXPRESS;Initial Catalog=joe;Integrated Security=True";
SqlConnection cn = new SqlConnection(conn);
SqlDataReader dr = null;
SqlCommand cm = new SqlCommand();
cm.Connection = cn;
cm.CommandType = CommandType.Text;
cm.CommandText = "select files from title where titileId=5";
cn.Open();
dr = cm.ExecuteReader();
byte[] File = null;
if (dr.Read())
{
File = (byte[])dr[0];
}
dr.Close();
cn.Close();
/*
* 直接另存为文件
*
*/
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
Stream myStream;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
using (BinaryWriter bw = new BinaryWriter(myStream))
{
// Add some text to the file.
bw.Write(File);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from db. Original error: " + ex.Message);
}
}
C#保存文件或读取数据库文件 另存为
原创
©著作权归作者所有:来自51CTO博客作者mb64be3e9157d3c的原创作品,请联系作者获取转载授权,否则将追究法律责任
下一篇:log4net使用详解
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
ios 聚合sdk
在第二篇聚合平台WebService技术中对如何成为聚合平台开发者,如何申请全国天气预报数据服务以及如何通过Java语言编写请求数据的常规方法。本篇研究如何通过集成聚合数据SDK来更加方便省事的获取各种数据,由于我们要开发的是气象助手项目,所以我们还是重点研究如何通过集成聚合数据SDK来获取全国天气预报相关数据,对于其它的数据大家可举一反三。一、聚合数据SDK说明 &n
ios 聚合sdk Android项目实战 Android开发 聚合数据 web service