加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将流写入文件无法正常工作

发布时间:2020-12-15 22:24:55 所属栏目:百科 来源:网络整理
导读:我正在制作一个程序,通过TCP传输文件块.现在,每次我在最后传输一个文件似乎都没有写入,所以如果我尝试传输图片 at the bottom right there are glitches. 现在,我的第一个想法是,当我读取,传输和写入比缓冲区长度更小的最终块时,我也写了很多零.所以我试着相
我正在制作一个程序,通过TCP传输文件块.现在,每次我在最后传输一个文件似乎都没有写入,所以如果我尝试传输图片 at the bottom right there are glitches.
现在,我的第一个想法是,当我读取,传输和写入比缓冲区长度更小的最终块时,我也写了很多零.所以我试着相应地改变最后的缓冲区大小.然后我尝试使用一个只写有HELLO WORLD的小文本文件,但是当我将其写入,然后打开文件时,它是空的.

这是读取和发送代码,其中范围[0]是第一部分,范围[1]是最后一部分:

byte[] buffer = new byte[DATA_BUFF_SIZE];
using (Stream input = File.OpenRead(file.Path))
{
    Console.WriteLine("SENT PARTS # ");
    for (int i = range[0]; i <= range[1]; i++)
    {
        Console.Write("PART " + i + ",");

        if (i == range[1])
        {
            buffer = new byte[input.Length - input.Position];
        }

        input.Position = i * DATA_BUFF_SIZE;
        input.Read(buffer,buffer.Length);

        netStream.Write(buffer,buffer.Length);

    }
    Console.WriteLine("LENGTH = " + input.Length);
}

这是接收和编写代码:

int bytesReceived = 0;
int index = partRange.First;
int partNum = 0;
byte[] receiveBuffer = new byte[BUFF_SIZE];

if (index == partRange.Last)
{
    receiveBuffer = new byte[fileToDownload.Length - index * BUFF_SIZE];
}

while ((bytesReceived = netStream.Read(receiveBuffer,receiveBuffer.Length)) > 0)
{
    Console.Write("INDEX:" + index + ",");
    output.Position = index * BUFF_SIZE;
    output.Write(receiveBuffer,receiveBuffer.Length);
    index++;
    partNum++;

    if (partNum > (partRange.Last - partRange.First))
    {
        break;
    }

    if (index == partRange.Last)
    {
        receiveBuffer = new byte[fileToDownload.Length - index * BUFF_SIZE];
    }
}
Console.WriteLine();

我错过了什么?我甚至在客户端和服务器上打印出缓冲区,它是相同的.

任何帮助将不胜感激,谢谢.

解决方法

试试netStream.Flush();

我怀疑正在发生的事情是在写完成之前流正在关闭.有时输出流将继续异步写入.在处理文件流时也会发现这一点.在继续执行之前,使用Flush()强制流完成它正在执行的任何写操作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读