我在使用用于将文件下载到调用HTTPHandler.ashx文件的web方法时遇到问题。处理程序调用webmethod如下:
byte[] docContent;
string fileType;
string fileName;
string msgInfo = brokerService.DownloadFile(trimURL, recNumber, out docContent, out fileType, out fileName);
在被调用的web方法中,我必须在使用之前初始化字节数组,否则我会在所有返回语句中出现编译器错误:
The out parameter 'docContents' must be assigned to before control leaves the current method
我尝试将其设置为空数组,但这会导致Buffer.BlockCopy方法失败:
Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.
mscorlib
at System.Buffer.BlockCopy(Array src, Int32 srcOffset, Array dst, Int32 dstOffset, Int32 count)
我知道我需要初始化它,但在访问数据库之前我不知道所需数组的长度。通过调试,我验证了所有代码的工作原理,除了Buffer.BlockCopy:
public string DownloadFile(string trimURL
, string TrimRecordNumber
, out byte[] docContents
, out string returnFiletype
, out string returnFilename)
{
docContents = new byte[0];
returnFiletype = null; returnFilename = null;
try
{
ConnectToTrim(trimURL);
if (!db.IsValid)
return "CRITICAL: Database Is NOT Valid";
Record myRec = db.GetRecord(TrimRecordNumber);
if (myRec == null)
return "CRITICAL: Record not found.";
uint bufferSize = 10000;
int documentLength = myRec.DocumentSize;
byte[] result = new byte[documentLength];
byte[] buffer = new byte[bufferSize];
uint bytesRead;
uint totalBytesRead = 0;
TRIMSDK.IStream docStream = myRec.GetDocumentStream(string.Empty, false, string.Empty);
while (totalBytesRead < documentLength)
{
docStream.RemoteRead(out buffer[0], 10000, out bytesRead);
for (int i = 0; i < bytesRead; i++)
{
result[totalBytesRead] = buffer[i];
totalBytesRead += 1;
}
}
returnFiletype = myRec.Extension;
returnFilename = myRec.SuggestedFileName;
Buffer.BlockCopy(result, 0, docContents, 0, result.Length);
return string.Format("OK-Document for recordnumber({0}): {1}.{2} - size: {3} bytes",
TrimRecordNumber, returnFilename, returnFiletype, Convert.ToString(documentLength));
}
catch (Exception ex)
{
return LogException(ex, "CRITICAL: Exception in DownloadFile method has been logged:", trimURL, 100);
}
}
答案 0 :(得分:5)
您可以从初始化为null开始。在调用Buffer.BlockCopy
之前,请将其分配并初始化为适当的长度。
这看起来像是:
public string DownloadFile(string trimURL
, string TrimRecordNumber
, out byte[] docContents
, out string returnFiletype
, out string returnFilename)
{
docContents = null;
//...
returnFiletype = myRec.Extension;
returnFilename = myRec.SuggestedFileName;
docContents = new byte[result.Length]; // Allocate appropriately here...
Buffer.BlockCopy(result, 0, docContents, 0, result.Length);
return ...
或者,您可以直接将结果分配并复制到docContents
- 完全不需要result
。但是,如果您想单独保留整体流控制,则仍需要在开始时{1}}初始化。