Joh*_*ams 1 c# bytearray out-parameters
我遇到了一个用于将文件下载到调用HTTPHandler.ashx文件的web方法的问题.处理程序调用webmethod如下:
byte[] docContent;
string fileType;
string fileName;
string msgInfo = brokerService.DownloadFile(trimURL, recNumber, out docContent, out fileType, out fileName);
Run Code Online (Sandbox Code Playgroud)
在被调用的webmethod中,我必须在使用它之前初始化字节数组,否则我会在所有return语句中出现编译器错误:
The out parameter 'docContents' must be assigned to before control leaves the current method
Run Code Online (Sandbox Code Playgroud)
我尝试将其设置为空数组,但这会导致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)
Run Code Online (Sandbox Code Playgroud)
我知道我需要初始化它,但我不知道在访问数据库之前所需的数组长度.通过调试我验证了所有代码的工作原理,除了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);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以从初始化为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 ...
Run Code Online (Sandbox Code Playgroud)
或者,您可以直接分配和复制结果docContents- result完全消除需要.但是,null如果您想单独保留整体流量控制,则仍需要在开始时进行初始化.
| 归档时间: |
|
| 查看次数: |
4065 次 |
| 最近记录: |