如何将大文件写入SQL Server FILESTREAM?

cha*_*ase 13 .net c# sql-server stream

我在向SQL Server上的FILESTREAM列写入大量数据时遇到问题.具体而言,围绕1.5-2GB小巧的文件的处理很好,但是当规模达到6GB和起来,我得到间歇性 IOException "句柄是无效的"关于.CopyTo()对传输结束.

我想过在块写入数据,但允许将数据追加到它,这破坏了完全的大文件的性能之前的SQL Server副本领域的备份文件.

这是代码:

public long AddFragment (string location , string description = null) 
{
    const string sql = 
        @"insert into [Fragment] ([Description],[Data]) " +
            "values (@description,0x); " +
         "select [Id], [Data].PathName(), " +
             "GET_FILESTREAM_TRANSACTION_CONTEXT() " +
         "from " +
             "[Fragment] " +
         "where " +
             "[Id] = SCOPE_IDENTITY();";

    long id;

    using (var scope = new TransactionScope(
        TransactionScopeOption.Required, 
            new TransactionOptions {
                Timeout = TimeSpan.FromDays(1)
            })) 
    {
        using (var connection = new SqlConnection(m_ConnectionString)) 
        {
            connection.Open();

            byte[] serverTx;
            string serverLocation;

            using (var command = new SqlCommand (sql, connection)) 
            {
                command.Parameters.Add("@description", 
                    SqlDbType.NVarChar).Value = description;

                using (var reader = command.ExecuteReader ()) 
                {
                    reader.Read();
                    id = reader.GetSqlInt64(0).Value;
                    serverLocation = reader.GetSqlString (1).Value;
                    serverTx = reader.GetSqlBinary (2).Value;
                }
            }

            using (var source = new FileStream(location, FileMode.Open, 
                FileAccess.Read, FileShare.Read, 4096, 
                FileOptions.SequentialScan))
            using (var target = new SqlFileStream(serverLocation, 
                serverTx, FileAccess.Write))
            {
                source.CopyTo ( target );
            }
        }

        scope.Complete();
    }

    return id;
}
Run Code Online (Sandbox Code Playgroud)

dmp*_*lla 5

我建议您在FileStream类周围使用BufferedStream类。

还要确保在SqlFileStream类上设置WriteTimeOut属性。

在这里你可以找到一篇非常好的文章,解释了有关 SqlFileStream 的所有内容http://www.simple-talk.com/sql/learn-sql-server/an-introduction-to-sql-server-filestream/