C#实现文件转二进制并存储到数据库
本文将详细讲解如何在C#应用程序中实现文件的上传与下载功能,核心步骤包括使用 OpenFileDialog 获取文件路径,通过 FileStream 和 BinaryReader 将文件读取为 Byte 数组,利用 ADO.NET 和 SQL 参数化查询将其安全地存入 SQL Server 数据库;反之亦然,通过 SqlDataAdapter 检索二进制流并使用 BinaryWriter 还原文件。
环境准备与前提条件
为了确保代码顺利运行,请确保满足以下条件:
- 开发环境:Visual Studio 或支持 .NET Framework/.NET Core 的 IDE。
- 目标平台:Windows Forms (WinForms) 应用程序。
- 数据库:已安装的 SQL Server(示例中使用本地服务器
server=.)。 - 表结构:数据库中需存在用于存储数据的表(示例中为
pro_table),包含以下列:
pro_name:nvarchar类型,用于存储文件名标识。pro_file:varbinary(max)类型,用于存储文件二进制数据。
操作步骤详解
第1步:添加必要的引用
在程序文件的头部添加以下命名空间引用,以便使用文件对话框、IO 操作及数据库连接类:
using System;
using System.IO;
using System.Windows.Forms;
using System.Data.SqlClient;
第2步:浏览并选择文件
通过调用 OpenFileDialog 允许用户选择要保存的文件,并将选中的文件路径赋值给文本框(如 textBox1),供后续步骤使用。
//这个方法是浏览文件对象
private void button1_Click(object sender, EventArgs e)
{
//用户打开文件浏览
using (OpenFileDialog dialog = new OpenFileDialog())
{
//只能单选一个文件
dialog.Multiselect = false;
//选择一个文件
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
//把选择的文件路径给txtPath
this.textBox1.Text = dialog.FileName;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
第3步:将文件转换为二进制并存入数据库
此方法读取选定的文件内容,将其转换为字节数组,然后通过 SqlCommand 的参数化方式插入数据库,以防止 SQL 注入并确保效率。
//把文件转成二进制流入出入数据库
private void button2_Click(object sender, EventArgs e)
{
string filePath = textBox1.Text;
// 检查文件路径是否有效
if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
{
MessageBox.Show("请先选择一个有效的文件!");
return;
}
FileStream fs = new FileStream(filePath, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
// 读取所有字节
Byte[] byData = br.ReadBytes((int)fs.Length);
fs.Close();
// 数据库连接字符串,请根据实际环境修改
string connStr = "server=.;database=testDB;Uid=sa;Pwd=sa";
using (SqlConnection myconn = new SqlConnection(connStr))
{
myconn.Open();
string str = "insert into pro_table (pro_name,pro_file) values('测试文件',@file)";
SqlCommand mycomm = new SqlCommand(str, myconn);
// 定义参数类型为 Binary,长度设为动态字节长度
mycomm.Parameters.Add("@file", SqlDbType.VarBinary, byData.Length).Value = byData;
mycomm.ExecuteNonQuery();
}
}
第4步:从数据库读取二进制并还原为文件
编写一个方法从数据库中提取 pro_file 字段,将其写入指定的磁盘路径以生成原始文件。
//从数据库中把二进制流读出写入还原成文件
private void button4_Click(object sender, EventArgs e)
{
string connStr = "server=.;database=testDB;Uid=sa;Pwd=sa";
string sql = "select pro_file from pro_table where pro_name='测试文件'";
DataSet myds = new DataSet();
using (SqlConnection myconn = new SqlConnection(connStr))
using (SqlDataAdapter sda = new SqlDataAdapter(sql, myconn))
{
sda.Fill(myds);
}
// 检查是否有数据返回
if (myds.Tables.Count > 0 && myds.Tables[0].Rows.Count > 0)
{
Byte[] Files = (Byte[])myds.Tables[0].Rows[0]["pro_file"];
// 指定输出的文件路径(D盘根目录下的2.rdlc)
string outputPath = "D:\\2.rdlc";
using (BinaryWriter bw = new BinaryWriter(File.Open(outputPath, FileMode.Create)))
{
bw.Write(Files);
}
MessageBox.Show("文件已成功还原!");
}
else
{
MessageBox.Show("未找到相关数据!");
}
}
完成判断
操作完成后,您可以通过检查目标位置的文件是否存在来验证成功与否;同时,确认数据库中新增了相应记录且无报错即可。
总结
以上就是 C#实现文件与二进制互转并存入数据库的详细内容,更多关于 C#文件存取及数据库操作的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









