博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#各种扩展名文件存入sql server数据库及读取到本地文件
阅读量:6349 次
发布时间:2019-06-22

本文共 6735 字,大约阅读时间需要 22 分钟。

sql server表结构如下:

create table DataTable(Id int identity(1,1) not null primary key,FileName nvarchar(100) not null,FilePath nvarchar(200) not null,Data varbinary(MAX) )

主要方法:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;using System.Data;using System.Data.SqlClient;using System.Windows.Forms;using System.Drawing;namespace DataAccess{    public class PubFunction    {        ///         /// 把文件存入数据库        ///         /// 文件路径(含文件名)        /// 
存入是否成功
public static bool StoreFiles(string[] filePaths) { try { for (int i = 0; i < filePaths.Length; i++) { string filePath = filePaths[i]; string fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1); using (SqlConnection connection = new SqlConnection(PubVariant.ConnectionString)) { connection.Open(); FileStream pFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); byte[] bytes = new byte[pFileStream.Length]; pFileStream.Read(bytes, 0, (int)pFileStream.Length); string strSql = "insert into DataTable(FileName,FilePath,Data) values(@FileName,@FilePath,@Data)"; using (SqlCommand cmd = new SqlCommand(strSql, connection)) { cmd.Parameters.Add("@FileName", SqlDbType.Text); cmd.Parameters.Add("@FilePath", SqlDbType.Text); cmd.Parameters.Add("@Data", SqlDbType.Binary); cmd.Parameters["@FileName"].Value = fileName; cmd.Parameters["@FilePath"].Value = filePath; cmd.Parameters["@Data"].Value = bytes; cmd.ExecuteNonQuery(); } } } return true; } catch (Exception ex) { MessageBox.Show(ex.Message); return false; } } /// /// 将数据库中数据写入文件 /// /// 用于查找数据的文件名 /// 目标文件路径(含文件名) ///
写入是否成功
public static bool WriteFromDBtoFile(string fileName, string destFilePath) { FileStream pFileStream = null; try { using (SqlConnection connection = new SqlConnection(PubVariant.ConnectionString)) { connection.Open(); string strSql0 = "select Data from DataTable where FileName = '{0}'"; string strSql1 = String.Format(strSql0, fileName); SqlCommand cmd = new SqlCommand(strSql1, connection); SqlDataReader dr = cmd.ExecuteReader(); dr.Read(); byte[] bytes = (byte[])dr[0]; pFileStream = new FileStream(destFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); pFileStream.Write(bytes, 0, bytes.Length); } return true; } catch (Exception ex) { MessageBox.Show(ex.Message); return false; } finally { if (pFileStream != null) { pFileStream.Close(); } } } public static DataTable GetDataFromSql(string strSql) { using (SqlConnection connection = new SqlConnection(PubVariant.ConnectionString)) { using (SqlCommand cmd = new SqlCommand(strSql, connection)) { using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { using (DataSet ds = new DataSet()) { da.Fill(ds); DataTable dt = ds.Tables[0]; return dt; } } } } } }}
具体实现:

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 DataAccess{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void textBox1_MouseClick(object sender, MouseEventArgs e)        {            OpenFileDialog ofd = new OpenFileDialog();            ofd.Multiselect = true;            ofd.InitialDirectory = "F:\\";            ofd.Filter = "All files(*.*)|*.*";            ofd.Title = "选择文件";            ofd.ShowDialog();            PubVariant.filePaths = ofd.FileNames;            listBox1.DataSource = PubVariant.filePaths;        }        private void btnSave_Click(object sender, EventArgs e)        {            if(PubFunction.StoreFiles(PubVariant.filePaths))            {                MessageBox.Show("Succeed!");            }        }        private void textBox2_MouseClick(object sender, MouseEventArgs e)        {            SaveFileDialog sfd = new SaveFileDialog();            sfd.Filter = "All files(*.*)|*.*";            sfd.Title = "保存文件";            sfd.InitialDirectory = "F:\\";            sfd.FileName = comboBox1.Text;            sfd.ShowDialog();            textBox2.Text = sfd.FileName;            PubVariant.saveFilePath = sfd.FileName;        }        private void button1_Click(object sender, EventArgs e)        {            string fileName = comboBox1.Text;            if(PubFunction.WriteFromDBtoFile(fileName,PubVariant.saveFilePath))            {                MessageBox.Show("Succeed!");            }        }        private void comboBox1_MouseClick(object sender, MouseEventArgs e)        {            string strSql = "select FileName from DataTable";            DataTable dt = PubFunction.GetDataFromSql(strSql);            for (int i = 0; i < dt.Rows.Count; i++)            {                comboBox1.Items.Add(dt.Rows[i][0].ToString());            }        }    }}
全局变量:

public class PubVariant    {        public static string[] filePaths;        public static string saveFilePath;        public static string connectionString = "server=eagle;database=Test;user id = sa;password=123456";        public static string ConnectionString        {            get { return connectionString; }            set { connectionString = value; }        }    }
实现效果如图:

转载:http://blog.csdn.net/foreverling/article/details/37691273

你可能感兴趣的文章
一键lnmp脚本&&php扩展模块安装(适用于CENTOS6.X系列)
查看>>
二维观察---文字的裁剪
查看>>
矩形覆盖
查看>>
ICMP
查看>>
界面设计模式(第2版)(全彩)
查看>>
解决VMware Workstation错误:未能锁定文件
查看>>
CentOS6 手动编译升级 gcc
查看>>
memcached的安装与开启脚本
查看>>
zabbix 邮件报警 -- sendmail
查看>>
JavaScript异步编程
查看>>
tcpdump用法小记
查看>>
MySQL基础安全注意细节
查看>>
Oracle随机函数—dbms_random
查看>>
pvr 批量转换
查看>>
linux命令basename使用方法
查看>>
windows下开发库路径解决方案
查看>>
linux迁移mysql数据目录
查看>>
脚本源码安装LNMP
查看>>
Percona Server安装
查看>>
函数为左边表达式
查看>>