我在写入SQL Server的FILESTREAM列时遇到了问题,特别是对于大约1.5-2GB大小的文件可以正常处理,但当文件大小达到6GB或更大时,在传输末尾使用.CopyTo()
时会不时地出现间歇性IOException
错误,显示"The handle is invalid"。
我考虑过分段写入数据,但是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;
}
.CopyTo
调用,所有这些都只会增加一些开销。 - chase