如何将word文档插入sql server并将其下载到我的驱动器?(visual studio c# Windows应用

本文关键字:驱动器 visual 我的 studio 应用 Windows 下载 文档 word 插入 sql | 更新日期: 2023-09-27 18:04:51

谁能提供一个代码来插入word文档到SQL数据库并从SQL数据库下载它?(代码应该是visual studio c# Windows应用程序)

谢谢

如何将word文档插入sql server并将其下载到我的驱动器?(visual studio c# Windows应用

读取word文档作为字节数组,并将其作为blob数据存储在数据库中。对于下载,读取字节数组并将输出作为扩展名为

的文件流式传输。doc

假设您有这个表模式,并且您正在使用本地sql db:

CREATE TABLE [FileTable1]
(
    [filePath] VARCHAR(100),
    [data] VARBINARY(MAX)
)

下面是Insert的代码:

static void InsertFile(string filename)
{   
    SqlConnection conn = new SqlConnection("Server=(localdb)''v11.0 ; Initial Catalog = {your db name}; Integrated Security = SSPI");
    SqlCommand cmd = new SqlCommand("INSERT INTO FileTable1 VALUES (@filePath, @data)", conn);
    cmd.Parameters.AddWithValue("@filePath", Path.GetFileName(filename));
    cmd.Parameters.Add("@data", SqlDbType.VarBinary, -1).Value = File.ReadAllBytes(filename);
    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();
}

下面是插入的代码:

string filetoInsert = @"C:'Temp'Test1.docx"; 
InsertFile(filetoInsert);

可以从数据库中检索,如下所示:

static byte[] ReadFile(string filename)
{   
     SqlConnection conn= new SqlConnection("Server=(localdb)''v11.0 ; Initial Catalog = {your db name}; Integrated Security = SSPI");
    SqlCommand cmd = new SqlCommand("SELECT * FROM FileTable1 WHERE filePath=@filePath", conn);
    cmd.Parameters.AddWithValue("@filePath", filename);
    conn.Open();
    SqlDataReader rdr = cmd.ExecuteReader();
    rdr.Read();
    MemoryStream ms = new MemoryStream();
    long startIndex= 0;
    const int readSize= 256;
    while (true)
    {
        byte[] buffer = new byte[readSize];
        long bytesRead= rdr.GetBytes(1, startIndex, buffer, 0, readSize);
        ms.Write(buffer, 0, (int)bytesRead);
        startIndex += bytesRead;
        if (bytesRead != readSize) break;
    }
    conn.Close();
    byte[] byteArr = ms.ToArray();
    ms.Dispose();
    return byteArr;
}

一旦你从db中检索到数据,你可以把它保存在某个临时位置或你指定的位置。

    string fileToRetrieve = @"Test1.docx"; 
    var fileRetrieved = RetrieveFile(fileToRetrieve);
    string tempFile = @"C:'file'path'Retrived.docx";
    File.WriteAllBytes(tempFile, fileRetrieved);

以内存流(字节)的形式打开文件。将内存流保存到SQL表中—保存到定义为VARBINARY(MAX)的列中。要恢复文件,请反向执行相同的操作。网上有很多关于这些步骤的信息