从SQL Server FILETABLE检索的文件已损坏

时间:2017-03-07 15:49:04

标签: c# sql-server

我在SQL Server 2014上创建了一个FILETABLE,其中包含所有默认选项,其中包含用于检索数据的视图以及用于插入和删除文件的存储过程。请注意,数据库上未启用非事务性访问,因为文件不应在文件系统上可见。

问题在于,当我从表中检索文件并将其写入磁盘时,它与原始文件不同,并且无法使用相关程序打开。

视图代码:

SELECT stream_id, file_stream, name, CAST(creation_time AS DateTime) AS DateCreated, CAST(last_write_time AS DateTime) AS DateUpdated FROM dbo.DocumentFiles

插入程序的代码:

create PROCEDURE [dbo].[sp_DocumentFiles_create]
-- Add the parameters for the stored procedure here
@name nvarchar(255),
@data varbinary(max)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

-- Insert statements for procedure here
DECLARE @id uniqueidentifier;
set @id = NEWID();
insert into DocumentFiles (stream_id, file_stream, name) VALUES(@id, @data, @name);
select @id;
END

用于阅读的代码:

DocumentFile result = null;
            SqlCommand comm = new SqlCommand("SELECT * from DocumentView where stream_id = @id", conn);
            comm.Parameters.Add(new SqlParameter("@id", id));
            try
            {
                conn.Open();
                SqlDataReader reader = comm.ExecuteReader();
                while (reader.Read())
                {
                    result = new DocumentFile();
                    result.stream_id = (Guid)reader["stream_id"];
                    result.file_stream = (byte[])reader["file_stream"];
                    result.name = reader["name"].ToString();
                    result.DateCreated = Convert.ToDateTime(reader["DateCreated"]);
                    result.DateUpdated = Convert.ToDateTime(reader["DateUpdated"]);
                }
            }
            catch
            {

            }
            finally
            {
                conn.Close();
            }
            return result;

用于插入的代码:

public Guid? Insert(DocumentFile obj)
        {
            Guid? result = null;
            SqlCommand comm = new SqlCommand("sp_DocumentFiles_create", conn);
            comm.CommandType = System.Data.CommandType.StoredProcedure;
            comm.Parameters.Add(new SqlParameter("@name", obj.name));
            comm.Parameters.Add(new SqlParameter("@data", obj.file_stream));
            try
            {
                conn.Open();
                result = comm.ExecuteScalar() as Guid?;
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

我设法插入和检索完整的唯一文件是图像文件。我尝试使用各种ms office文档(.doc,.docx,.pptx等)以及档案(rar,zip)。

0 个答案:

没有答案