[英]File Transfer from one system to another in c#
我有一个客户端客户端从服务器接收文件的c#程序。 有时它可以无缝运行。 有时它在fileName = Encoding.ASCII.GetString(dataByte, 4, fileNameLen);
给出异常fileName = Encoding.ASCII.GetString(dataByte, 4, fileNameLen);
。
ArgumentOutOfRange Exception
Index and count must refer to a location within the buffer.
Parameter name: bytes
如果fileNameLen
值为8
或12
则它将正常工作。 否则将为1330795077
。 这是为什么? 谁能解释我为什么呢? 请。 这是我的代码。
string fileName = string.Empty;
int thisRead = 0;
int blockSize = 1024;
Byte[] dataByte = new Byte[blockSize];
lock (this)
{
string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\\";
ns.Read(dataByte, thisRead, blockSize);
int fileNameLen = BitConverter.ToInt32(dataByte, 0);
fileName = Encoding.ASCII.GetString(dataByte, 4, fileNameLen);
Stream fileStream = File.OpenWrite(folderPath + fileName);
fileStream.Write(dataByte, 4 + fileNameLen, (1024 - (4 + fileNameLen)));
while (true)
{
thisRead = ns.Read(dataByte, 0, blockSize);
fileStream.Write(dataByte, 0, thisRead);
if (thisRead == 0)
break;
}
fileStream.Close();
}
传输数据dataByte
,您需要检查其内容。 如果尝试从dataByte
创建整数并在fileNameLen
dataByte
转换为Int32,则可能会收到诸如1330795077
愚蠢值,并且这不是Encoding.ASCII.GetString(dataByte, 4, fileNameLen);
有效索引Encoding.ASCII.GetString(dataByte, 4, fileNameLen);
在您的代码中ns.Read(dataByte, thisRead, blockSize);
应该返回一个int值,指示实际读取的长度。 使用该返回值来控制要转换为字符串的字节数,以避免产生愚蠢的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.