繁体   English   中英

使用C#将文件从一个系统传输到另一个系统

[英]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值为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();
        }

索引和计数不表示有效范围(以字节为单位)。

Encoding.ASCII.GetString()

由于以下原因而引发ArgumentOutOfRangeException:

  • 索引或计数小于零。

  • 索引和计数不表示有效范围(以字节为单位)。

根据您的情况进行计数fileNameLen

文档指出:

要转换的数据(例如从流中读取的数据)只能在顺序块中可用。 在这种情况下,或者如果数据量太大以致需要将其划分为较小的块,则应用程序应分别使用由GetDecoder方法或GetEncoder方法提供的Decoder或Encoder。

请参阅说明文件

传输数据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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM