文件从c#中的一个系统传输到另一个系统

时间:2013-03-22 11:13:01

标签: c#

我有这个c#程序,它是一个客户端从服务器接收文件。有时它无缝地工作。有时它会在fileName = Encoding.ASCII.GetString(dataByte, 4, fileNameLen);中给出例外。

ArgumentOutOfRange Exception
Index and count must refer to a location within the buffer.
Parameter name: bytes

如果fileNameLen的值为812,那么它可以正常运行。否则它将是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();
        }

3 个答案:

答案 0 :(得分:3)

  

index和count不表示有效的字节范围。

<强> Encoding.ASCII.GetString()

由于以下原因而抛出ArgumentOutOfRangeException:

  • 索引或计数小于零。

  • 索引和计数不表示有效的字节范围。

计数就在你的情况下: fileNameLen

文档说明:

  

要转换的数据,例如从流中读取的数据,可以是   仅在顺序块中可用。在这种情况下,或者如果金额   数据是如此之大,以至于它需要被分成更小的块   应用程序应使用Decoder或由...提供的编码器   分别是GetDecoder方法或GetEncoder方法。

请参阅Documentation

答案 1 :(得分:2)

您需要在转移时查看dataByte的内容。如果您尝试从dataByte创建和整数并将其转换为fileNameLen中的Int32,则可能会收到1330795077这样的愚蠢值,这不是Encoding.ASCII.GetString(dataByte, 4, fileNameLen);的有效索引

答案 2 :(得分:0)

代码中的

ns.Read(dataByte, thisRead, blockSize);应返回一个int值,表示读取的实际长度。使用该返回值来控制要转换为字符串的字节数,以避免产生愚蠢的值。