接到任务 将文件使用二进制的方式存放在数据库的varbinary(max)的字段中,
以下是测试成功后的代码
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.IO;
- using System.Data.SqlClient;
- namespace SaveFileToDBForms
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void btnBrowse_Click(object sender, EventArgs e)
- {
- if (openFileDialog1.ShowDialog() == DialogResult.OK)
- {
- txtFilePath.Text = openFileDialog1.FileName;
- }
- }
- private void SubmitFileIntoDB()
- {
- if(txtFilePath.Text!=null)
- {
- string file = txtFilePath.Text;
- byte[] buffer = File.ReadAllBytes(file);
- using (SqlConnection conn = new SqlConnection(@"server=10.66.201.52\SQL2008R2;database=FGM_POS;uid=sa;pwd=123456sql"))
- {
- conn.Open();
- using (SqlCommand cmd=new SqlCommand())
- {
- cmd.Connection = conn;
- cmd.CommandText = "insert into FGM_bt_CouponFile(CouponFileData) values(@FileData)";
- cmd.Parameters.AddRange(
- new[]
- {
- new SqlParameter("@FileData",buffer)
- });
- //conn.Open();
- int count= cmd.ExecuteNonQuery();
- conn.Close();
- if (count > 0)
- {
- MessageBox.Show("OK");
- }
- }
- }
- }
- }
- private void btnSave_Click(object sender, EventArgs e)
- {
- SubmitFileIntoDB();
- }
- }
- }
note : 浏览按钮 btnBrowse
文件路径显示TextBox txtFilePath
将选择的文件保存到数据库按钮 btnSave
转载于:https://blog.51cto.com/3941954/761179