接到任务 将文件使用二进制的方式存放在数据库的varbinary(max)的字段中,

以下是测试成功后的代码

 

 
  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.IO;  
  10. using System.Data.SqlClient;  
  11.  
  12. namespace SaveFileToDBForms  
  13. {  
  14.     public partial class Form1 : Form  
  15.     {  
  16.         public Form1()  
  17.         {  
  18.             InitializeComponent();  
  19.         }  
  20.  
  21.         private void btnBrowse_Click(object sender, EventArgs e)  
  22.         {  
  23.             if (openFileDialog1.ShowDialog() == DialogResult.OK)  
  24.             {  
  25.                 txtFilePath.Text = openFileDialog1.FileName;  
  26.             }  
  27.         }  
  28.         private  void SubmitFileIntoDB()  
  29.         {   
  30.             if(txtFilePath.Text!=null)  
  31.             {  
  32.                 string file = txtFilePath.Text;  
  33.                 byte[] buffer = File.ReadAllBytes(file);  
  34.                 using (SqlConnection conn = new SqlConnection(@"server=10.66.201.52\SQL2008R2;database=FGM_POS;uid=sa;pwd=123456sql"))  
  35.                 {  
  36.                     conn.Open();  
  37.  
  38.                     using (SqlCommand cmd=new SqlCommand())  
  39.                     {  
  40.                         cmd.Connection = conn;  
  41.                         cmd.CommandText = "insert into FGM_bt_CouponFile(CouponFileData) values(@FileData)";  
  42.                         cmd.Parameters.AddRange(  
  43.                             new[]  
  44.                             {  
  45.                                 new SqlParameter("@FileData",buffer)  
  46.                             });  
  47.                         //conn.Open();  
  48.                         int countcmd.ExecuteNonQuery();  
  49.                         conn.Close();  
  50.                         if (count > 0)  
  51.                         {  
  52.                             MessageBox.Show("OK");  
  53.                         }  
  54.  
  55.                     }  
  56.                 }  
  57.             }  
  58.         }  
  59.  
  60.         private void btnSave_Click(object sender, EventArgs e)  
  61.         {  
  62.             SubmitFileIntoDB();  
  63.         }  
  64.     }  
  65. }  

note : 浏览按钮 btnBrowse

文件路径显示TextBox   txtFilePath

将选择的文件保存到数据库按钮 btnSave