C#各种扩展名文件存入sql server数据库及读取到本地文件

news/2024/7/4 0:44:30

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
    {
        /// <summary>
        /// 把文件存入数据库
        /// </summary>
        /// <param name="filePaths">文件路径(含文件名)</param>
        /// <returns>存入是否成功</returns>
        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;
            }            
        }

        /// <summary>
        /// 将数据库中数据写入文件
        /// </summary>
        /// <param name="fileName">用于查找数据的文件名</param>
        /// <param name="destFilePath">目标文件路径(含文件名)</param>
        /// <returns>写入是否成功</returns>
        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


http://www.niftyadmin.cn/n/4610390.html

相关文章

Java容器使用总结

版权声明&#xff1a;本文为博主原创或整理自网络&#xff0c;欢迎转载&#xff0c;转载请注明出处。 Collection ├List │├LinkedList │├ArrayList │└Vector │└Stack ├Queue │├Deque │└LinkedList └Set ├SortedSet ├TreeSet └HashSet Map ├H…

如何判断当前主机是物理机还是虚拟机

Windows&#xff1a;在CMD里输入&#xff1a;Systeminfo | findstr /i "System Model"如果System Model&#xff1a;后面含有Virutal就是虚拟机&#xff0c;其他都是物理机或者用powershell命令&#xff1a;get-wmiobject win32_computersystem | fl modelLinux&…

1081 Rational Sum (20分)【分数的四则运算】

1081 Rational Sum (20分) Given N rational numbers in the form numerator/denominator, you are supposed to calculate their sum. Input Specification: Each input file contains one test case. Each case starts with a positive integer N (≤100), followed in th…

记一次错误卸载软件包导致Linux系统崩溃的修复解决过程

首先问题产生的缘由很简单&#xff0c;是我一同事在安装oracle一套软件时&#xff0c;按照要求需要binutils软件包的32位版本&#xff0c;然而在Oracle Linux已经装有64位&#xff0c;按理说是可以安装i686的&#xff0c;我猜应该是32位的版本低于这个已有的64位所以导致冲突而…

个人作业—找水王

题目&#xff1a;三人行设计了一个灌水论坛。信息学院的学生都喜欢在上面交流灌水&#xff0c;传说在论坛上有一个“水王”&#xff0c;他不但喜欢发帖&#xff0c;还会回复其他ID发的每个帖子。坊间风闻该“水王”发帖数目超过了帖子数目的一半。如果你有一张当前论坛的帖子&a…

1059 Prime Factors (25分)【质因数分解】

1059 Prime Factors (25分) Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N p​1​​​k​1​​​​p​2​​​k​2​​​​⋯p​m​​​k​m​​​​. Input Specification: Each input file contain…

POJO百度百科

POJO(Plain Ordinary Java Object)简单的Java对象&#xff0c;实际就是普通JavaBeans&#xff0c;是为了避免和EJB混淆所创造的简称。 使用POJO名称是为了避免和EJB混淆起来, 而且简称比较直接. 其中有一些属性及其getter setter方法的类,没有业务逻辑&#xff0c;有时可以作为…

找出一个只出现一次的字符

一&#xff0c;问题描述 给定一个字符串&#xff0c;找出一个 其中只出现一次的字符 如"abaccdeff" 只出现一次的字符有 b d e 二&#xff0c;问题分析 ①字符集是个常量 &#xff0c;字符只有那么多。比如ASCII 一共256个&#xff0c;比如 字母表一共只有26个…