gpt4 book ai didi

c# - 从 WinForms C# 应用程序从 SQL Server 2005/2008 上传/下载文件?

转载 作者:太空狗 更新时间:2023-10-29 20:15:19 26 4
gpt4 key购买 nike

我正在使用 DocX 创建 .docx 文件。与其将它们存储在硬盘驱动器、Share 或 SharePoint 上,我更愿意将它们存储在 SQL 数据库中。所以我的问题是:

  1. 如何编写正确的代码将文件保存到该数据库?
  2. 如何编写正确的代码来将文件检索到该数据库?
  3. 我应该为表设置哪种数据类型来保存 docx 文件?是图片吗?

关于,

疯子

附言。在使用旧的“学校”方式方面,我更喜欢正确的代码:

using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetailsDepozyt))
using (var sqlQuery = new SqlCommand(preparedCommand, varConnection))
using (var sqlQueryResult = sqlQuery.ExecuteReader())
while (sqlQueryResult != null && sqlQueryResult.Read())

最佳答案

docx 文件就像一个 zip 文件,它是几个文件的集合。转换成二进制然后存入DB怎么样

下面的东西会起作用

保存

        string filePath = "";
string connectionString = "";
FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(stream);
byte[] file = reader.ReadBytes((int)stream.Length);
reader.Close();
stream.Close();

SqlCommand command;
SqlConnection connection = new SqlConnection(connectionString);
command = new SqlCommand("INSERT INTO FileTable (File) Values(@File)", connection);
command.Parameters.Add("@File", SqlDbType.Binary, file.Length).Value = file;
connection.Open();
command.ExecuteNonQuery();

检索有点复杂的过程如下

            SqlConnection connection = new SqlConnection("");
string query =
@" SELECT File FROM FileTable where FileID =" + 125;
SqlCommand command = new SqlCommand(query, connection);

FileStream stream;
BinaryWriter writer;

int bufferSize = 100;
byte[] outByte = new byte[bufferSize];

long retval;
long startIndex = 0;

string pubID = "";

connection.Open();
SqlDataReader reader = command.ExecuteReader(CommandBehavior.Default);

while (reader.Read())
{
pubID = reader.GetString(0);

stream =
new FileStream("abc.docx", FileMode.OpenOrCreate, FileAccess.Write);
writer = new BinaryWriter(stream);
startIndex = 0;
retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize);

while (retval == bufferSize)
{
writer.Write(outByte);
writer.Flush();
startIndex += bufferSize;
retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize);
}
writer.Write(outByte, 0, (int)retval - 1);
writer.Flush();
writer.Close();
stream.Close();
} reader.Close();
connection.Close();

查看以下文章以获得帮助和详细信息

保存:

检索 :

关于c# - 从 WinForms C# 应用程序从 SQL Server 2005/2008 上传/下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2259037/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com