我的App Server上有一个上传的文件,然后我使用SQLFileStream将其传输到MSSQL数据库,写入10mb(我已经尝试增加/减少这个)块。这适用于500mb及以下的文件但是更大的文件,当它到达文件的大约800mb时,我在The Handle is Invalid
行上收到错误filestream.Write(buffer, 0, buffer.Length);
。
我认为有些东西会在某个地方超时 - 有人能指出我正确的方向吗?方法如下
protected bool TransferFileToDB(string DocID, string filePath)
{
bool success = false;
// Get the file from the Upload Folder
FileInfo fi = new System.IO.FileInfo(filePath);
string conStr = GetConnectionString();
SqlConnection connection = new SqlConnection(conStr);
if (fi.Exists)
{
try
{
byte[] buffer;
long position = 0;
int packetSize = 10 * 1000 * 1024; // 10mb chunks
// Open the file for reading
using (FileStream fs = new FileStream(filePath, System.IO.FileMode.Open))
{
long length = fs.Length;
using (TransactionScope transactionScope = new TransactionScope())
{
string filePath = GetDocumentPath(DocID);
connection.Open();
SqlCommand sqlCommand = connection.CreateCommand();
sqlCommand.CommandText = "Select GET_FILESTREAM_TRANSACTION_CONTEXT()As TransactionContext";
byte[] transactionContext1 = (byte[])sqlCommand.ExecuteScalar();
using (SqlFileStream filestream = new SqlFileStream(filePath, transactionContext1, FileAccess.Write))
{
SqlParameter param = new SqlParameter();
while (position < length)
{
if (position + packetSize > length)
{
buffer = new byte[length - position];
}
else
{
buffer = new byte[packetSize];
}
//Read file
fs.Read(buffer, 0, buffer.Length);
//Copy to DB Server
filestream.Write(buffer, 0, buffer.Length);
filestream.Flush();
Debug.WriteLine("Copied to DB " + position.ToString());
position += buffer.Length;
}
filestream.Close();
}
transactionScope.Complete();
}
fs.Close();
}
// Once file has been sent to DB server, delete temp file on the App Server
fi.Delete();
return true;
}
catch (Exception e)
{
Debug.WriteLine("Error in TransferFileToDB" + e.Message + e.InnerException);
fi.Delete();
return false;
}
答案 0 :(得分:2)
最后想出了这个,所以这里是解决方案以防任何人碰到它。
TransactionScope似乎有超过60秒的默认时间,因此在构造函数中传递时间值解决了我的所有问题
using (TransactionScope transactionScope = new TransactionScope
(TransactionScopeOption.Required, TimeSpan.FromHours(1)))
http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope(v=vs.110).aspx