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

本文涉及的产品
云数据库 RDS SQL Server,基础系列 2核4GB
简介:

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

目录
相关文章
|
3月前
|
SQL 机器学习/深度学习 人工智能
从“写SQL”到“聊数据”:NL2SQL如何用自然语言解锁数据库?
本文系统性地阐述了自然语言转SQL(NL2SQL) 技术如何让非技术背景的业务分析师实现数据自助查询,从而提升数据驱动决策的效率与准确性。
从“写SQL”到“聊数据”:NL2SQL如何用自然语言解锁数据库?
|
2月前
|
SQL 人工智能 Linux
SQL Server 2025 RC1 发布 - 从本地到云端的 AI 就绪企业数据库
SQL Server 2025 RC1 发布 - 从本地到云端的 AI 就绪企业数据库
351 5
SQL Server 2025 RC1 发布 - 从本地到云端的 AI 就绪企业数据库
|
1月前
|
SQL 存储 监控
SQL日志优化策略:提升数据库日志记录效率
通过以上方法结合起来运行调整方案, 可以显著地提升SQL环境下面向各种搜索引擎服务平台所需要满足标准条件下之数据库登记作业流程综合表现; 同时还能确保系统稳健运行并满越用户体验预期目标.
180 6
|
3月前
|
SQL 人工智能 Java
用 LangChain4j+Ollama 打造 Text-to-SQL AI Agent,数据库想问就问
本文介绍了如何利用AI技术简化SQL查询操作,让不懂技术的用户也能轻松从数据库中获取信息。通过本地部署PostgreSQL数据库和Ollama模型,结合Java代码,实现将自然语言问题自动转换为SQL查询,并将结果以易懂的方式呈现。整个流程简单直观,适合初学者动手实践,同时也展示了AI在数据查询中的潜力与局限。
417 8
|
3月前
|
SQL 人工智能 Linux
SQL Server 2025 RC0 发布 - 从本地到云端的 AI 就绪企业数据库
SQL Server 2025 RC0 发布 - 从本地到云端的 AI 就绪企业数据库
261 5
|
8月前
|
SQL Java 数据库连接
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
|
4月前
|
SQL 缓存 监控
SqlRest让SQL秒变Http API,还支持20+数据库(含国产数据库)
杭州奥零数据科技有限公司成立于2023年,专注于数据中台业务,维护开源项目AllData并提供商业版解决方案。AllData提供数据集成、存储、开发、治理及BI展示等一站式服务,支持AI大模型应用,助力企业高效利用数据价值。
|
4月前
|
SQL 存储 数据库
SQL Server Management Studio (SSMS) 21 - 微软数据库管理工具
SQL Server Management Studio (SSMS) 21 - 微软数据库管理工具
916 0
|
4月前
|
SQL XML Java
配置Spring框架以连接SQL Server数据库
最后,需要集成Spring配置到应用中,这通常在 `main`方法或者Spring Boot的应用配置类中通过加载XML配置或使用注解来实现。
433 0
|
6月前
|
存储 监控 算法
基于 C# 的局域网计算机监控系统文件变更实时监测算法设计与实现研究
本文介绍了一种基于C#语言的局域网文件变更监控算法,通过事件驱动与批处理机制结合,实现高效、低负载的文件系统实时监控。核心内容涵盖监控机制选择(如事件触发机制)、数据结构设计(如监控文件列表、事件队列)及批处理优化策略。文章详细解析了C#实现的核心代码,并提出性能优化与可靠性保障措施,包括批量处理、事件过滤和异步处理等技术。最后,探讨了该算法在企业数据安全监控、文件同步备份等场景的应用潜力,以及未来向智能化扩展的方向,如文件内容分析、智能告警机制和分布式监控架构。
188 3

热门文章

最新文章