111,125
社区成员
发帖
与我相关
我的任务
分享//读取word并存入sql数据库
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "doc文件(*.doc)|*.doc|所有文件(*.*)|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (openFileDialog1.FileName != "")
{
//存入代码
FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open);
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, (int)fs.Length);
fs.Close();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "server=localhost; database=hyz; User ID=sa;trusted_connection=true";
conn.Open();
SqlCommand com = new SqlCommand();
com.Connection = conn;
com.CommandText = "insert into test values('1', @t1)";
SqlParameter param = new SqlParameter();
param.ParameterName = "t1";
param.SqlDbType = SqlDbType.Binary;
param.Value = bytes;
com.Parameters.Add(param);
com.ExecuteNonQuery();
conn.Close();
//读取代码
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "server=localhost; database=hyz; User ID=sa;trusted_connection=true";
conn.Open();
SqlCommand com = new SqlCommand();
com.Connection = conn;
com.CommandText = "select doc from test where id='1'";
object obj = com.ExecuteScalar();
conn.Close();
byte[] bytes = obj as byte[];
string szFileName = Application.StartupPath + "\\test.doc";
if (!File.Exists(szFileName))
File.Create(szFileName);
FileStream fs = new FileStream(szFileName, FileAccess.Write);
fs.Write(bytes, 0, bytes.Length);
fs.Close();
fs.Dispose();
}
}