如何将文件从SqlFilestream显示到wpf文档查看器中

时间:2016-08-31 07:51:21

标签: c# sql sql-server wpf

我将docx文件插入到SQL表中,如

DECLARE @file AS VARBINARY(MAX) 

SELECT @file = CAST(bulkcolumn AS VARBINARY(MAX))
      FROM OPENROWSET(
            BULK
            'D:\abc.docx',
            SINGLE_BLOB ) AS x

INSERT INTO ItemData(Id,fileData)

SELECT NEWID(),@file 

现在文件已正确插入表格。

读取文件

对于阅读文件,我使用的是以下代码: " ItemNumber"用于身份。 一切都很好。 但是我必须在WPF中向文档查看器显示该文件。

            string cmdString = "Select fileData.PathName() As Path from ItemData where ItemNumber = '" + itemNumber + "' ";
            SqlCommand cmd = new SqlCommand(cmdString, conn);
            Object pathObj = cmd.ExecuteScalar();
            if (DBNull.Value != pathObj)
                filePath = (string)pathObj;
            else
            {
                throw new System.Exception("fileData.PathName() failed to read the path name for the Chart column.");
            }

            this.wbControl.Navigate(filePath);

            SqlTransaction transaction = conn.BeginTransaction("mainTranaction");
            cmd.Transaction = transaction;
            cmd.CommandText = "SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()";

            Object obj = cmd.ExecuteScalar();
            byte[] txContext = (byte[])obj;

            SqlFileStream sqlFileStream = new SqlFileStream(filePath, txContext, FileAccess.ReadWrite);
            //byte[] buffer2 = new byte[(int)sqlFileStream.Length];

            byte[] buffer = new byte[512];
            int numBytes = 0;
            string someData = "EKG data.";
            Encoding unicode = Encoding.GetEncoding(0);

            sqlFileStream.Write(unicode.GetBytes(someData.ToCharArray()), 0, someData.Length);

            sqlFileStream.Seek(0L, SeekOrigin.Begin);
            numBytes = sqlFileStream.Read(buffer, 0, buffer.Length);
            string readData = unicode.GetString(buffer);

            if (numBytes != 0)                    
                Console.WriteLine(readData);

            //Because reading and writing are finished, FILESTREAM 
            //must be closed. This closes the c# FileStream class, 
            //but does not necessarily close the the underlying 
            //FILESTREAM handle. 
            sqlFileStream.Close();

            //The final step is to commit or roll back the read and write
            //operations that were performed on the FILESTREAM BLOB.

            cmd.Transaction.Commit();

如何在WPF中向文档查看器显示SqlFileStream

我将docx文件存储在数据库中。

0 个答案:

没有答案