1

我正在通过 NetworkStream 传输文件,似乎当文件超过 5-10k 时,文件开始丢失数据和/或有巨大的空白间隙。

这是我所拥有的:

private string ReadandSaveFileFromServer(TcpClient clientATF, NetworkStream currentStream, string locationToSave)
{
    int fileSize = 0;
    string fileName = "";
    int bytesRead = 0;

    fileName = ReadStringFromServer(clientATF, currentStream);
    fileSize = ReadIntFromServer(clientATF, currentStream);

    FileStream fs = new FileStream(locationToSave + "\\" + fileName, FileMode.Create);

    byte[] fileSent = new byte[fileSize];

    while (currentStream.DataAvailable)
    {
        if (clientATF.Connected)
        {
            bytesRead = currentStream.Read(fileSent, 0, fileSent.Length);
            fs.Write(fileSent, 0, fileSent.Length);
        }
        else
        {
            break;
        }
    }

    fs.Flush();
    fs.Close();

    return fileName;
}
4

4 回答 4

2

不,你写错了缓冲区代码。乍一看,我建议您改为fs.Write(fileSetn, 0, bytesRead)改为。

于 2010-10-13T00:21:11.360 回答
2

这是问题所在:fs.Write(fileSent, 0, fileSent.Length);

fileSent.Length在获得字节时将字节写入文件bytesRead

更正的代码:

fs.Write(fileSent, 0, bytesRead);
于 2010-10-13T00:22:21.527 回答
0

摆脱可用的测试并阅读,直到获得 EOS。这是对可用的滥用。

于 2010-10-13T00:32:00.077 回答
0

这是答案。fs.Write() 错误是我的疏忽。感谢大家的帮助。

  private string ReadandSaveFileFromServer(TcpClient clientATF, NetworkStream currentStream, string locationToSave)
    {
        int fileSize = 0;
        string fileName = "";
        int bytesRead = 0;

        fileName = ReadStringFromServer(clientATF, currentStream);
        fileSize = ReadIntFromServer(clientATF, currentStream);

        FileStream fs = new FileStream(locationToSave + "\\" + fileName, FileMode.Create);

        byte[] fileSent = new byte[fileSize];

        while (fs.Length != fileSize)
        {

                bytesRead = currentStream.Read(fileSent, 0, fileSent.Length);
                fs.Write(fileSent, 0, bytesRead);

        }

        fs.Flush();
        fs.Close();

        return fileName;
    }
于 2010-10-14T16:48:31.657 回答