gpt4 book ai didi

c# - C# 将文件从一个系统传输到另一个系统

转载 作者:行者123 更新时间:2023-12-02 22:09:28 24 4
gpt4 key购买 nike

我有这个 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();
}

最佳答案

index and count do not denote a valid range in bytes.

Encoding.ASCII.GetString()

ArgumentOutOfRangeException 抛出是因为以下原因:

  • 索引或计数小于零。

  • index 和 count 不表示以字节为单位的有效范围。

Count 在您的情况下:fileNameLen

文档指出:

Data to be converted, such as data read from a stream, can be available only in sequential blocks. In this case, or if the amount of data is so large that it needs to be divided into smaller blocks, the application should use the Decoder or the Encoder provided by the GetDecoder method or the GetEncoder method, respectively.

参见 Documentation

关于c# - C# 将文件从一个系统传输到另一个系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15568926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com