c从一个系统到另一个系统的文件传输#
问题描述:
我有这个c#程序,它是一个客户端从服务器接收文件。有时它可以无缝工作。有时在fileName = Encoding.ASCII.GetString(dataByte, 4, fileNameLen);
中有例外。c从一个系统到另一个系统的文件传输#
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();
}
答
指数和计数不表示以字节为单位的有效范围。
Encoding.ASCII.GetString()
ArgumentOutOfRangeException被抛出怎么一回事,因为对以下原因:
索引或计数小于零。
索引和计数不表示字节中的有效范围。
计数是你的情况:fileNameLen
文档状态:
数据要转换,例如从一个流中读取数据,可以是仅 可用在顺序块。在这种情况下,或者如果 的数据量是如此之大,它需要被分成更小的块,则 应用程序应使用Decoder或分别由 GetDecoder方法或GetEncoder方法,所提供的编码器。
答
您将需要检查的dataByte
内容时,它已经被转移。如果你想创建和dataByte
整数,你将它转换为的Int32在fileNameLen
您可能会收到傻值像1330795077
这是没有有效的索引,在您的代码ns.Read(dataByte, thisRead, blockSize);
Encoding.ASCII.GetString(dataByte, 4, fileNameLen);
答
应该返回一个int值表示的实际长度读。使用该返回值来控制要转换为字符串的字节数,以避免创建愚蠢的值。