【问题标题】:sqlfilestream - getting blob data from SQL Server and saving the file locally to disksqlfilestream - 从 SQL Server 获取 blob 数据并将文件本地保存到磁盘
【发布时间】:2017-03-30 20:36:27
【问题描述】:

我有以下场景:

我已使用 FILESTREAM 成功地将我的文件(各种扩展名)保存到我的 sql server 数据库中。这些可以是任何东西,从图像到 word doc、pdf 等。

现在我想检索它们并将它们作为文件保存到我的本地目录。

这是我目前所拥有的

我的函数调用 SQL 并获取我想要的文件流信息

    public static void SelectFile(string sourceId)
    {
        string serverPath;
        string filename;
        byte[] serverTxn;

        using (TransactionScope ts = new TransactionScope())
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["DBConn"].ToString()))
            {
                conn.Open();

                using (SqlCommand cmd = new SqlCommand("OPS.LoadFileBlobFromSQL", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@AttachmentId", SqlDbType.VarChar).Value = sourceId;

                    using (SqlDataReader rdr = cmd.ExecuteReader())
                    {
                        rdr.Read();
                        filename = rdr.GetSqlString(0).Value;
                        serverPath = rdr.GetSqlString(1).Value;
                        serverTxn = rdr.GetSqlBinary(2).Value;
                        rdr.Close();
                    }
                }
               StreamObjectFromFilestream(serverPath, serverTxn, filename);
            }
            ts.Complete();
        }
    }

    private static void StreamObjectFromFilestream(string serverPath, byte[] serverTxn, string filename)
    {
        SqlFileStream sfs = new SqlFileStream(serverPath, serverTxn, FileAccess.Read);
        byte[] buffer = new byte[sfs.Length];
        sfs.Read(buffer, 0, buffer.Length);

        System.IO.File.WriteAllBytes(@"c:\test\hello.pdf", buffer);
        sfs.Close();
    }

我正在获取服务器路径、文件名和 serverTxn .. 但是当我进入我的 StreamObjectFromFilestream 函数时,缓冲区是空的。我知道我在这里遗漏了一些简单的东西......只是不知道是什么。

任何正确方向的指针将不胜感激。

谢谢, 科里

【问题讨论】:

    标签: c# sql-server sqlfilestream flatfiledestination


    【解决方案1】:

    您可以跳过使用 StreamObjectFromFilestram 中的 SqlFilestream,您的 serverTxn 已经是方法 WriteAllBytes 需要的字节数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-24
      • 2011-06-26
      • 1970-01-01
      • 2010-12-03
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多