读取文件字节数已完成 [英] Read Bytes of Files Complete

查看:94
本文介绍了读取文件字节数已完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们

我有一个使用套接字的简单文件传输应用程序
我的问题是发送文件的字节数
此代码发送15Mb文件的整个字节,但仅发送20-40 kb的2mb文件
或750 kb的30-50 kb

我认为问题出在File.ReadAllbyte()
所以我用了Thread.Sleep(5000)

但结果是一样,变化不大

如何强制将整个文件填充为byte []?

private void StartSendingData(IPAddress ServerIP, string FileName)
{
    Socket MySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    byte[] bt = File.ReadAllBytes(FileName);
    //Thread.Sleep(5000);
    MySocket.Connect(new IPEndPoint(ServerIP, 33000));
    MySocket.Send(bt);

}

解决方案

File.ReadAllBytes 应该读取指定字节数组中的所有二进制文件内容,确定不会?!?!无论如何,如果我是你,我不会那样做!我不会以一个字节的数组读取文件的所有内容,特别是当文件是大文件时,这会使缓冲区的大小与文件的大小确实不符.

更好的方法是开始读取大小为1k或2k的小缓冲区块中的文件内容,然后开始依次发送每个块. ReadAllBytes应该在进入下一行代码之前将整个文件读入内存.您的网络代码可能有问题.

读取所有字节后,检查字节数组的长度.并检查从Send()方法返回的值...这将是发送的字节数.如果它没有返回从文件加载的字节数,那么您就知道问题出在哪里.您还应该检查该Send()的接收端,以查看接收到多少个字节...这还可以提供一些有关正在发生什么情况的线索.


hi guys

I have a simple File transfer application that use socket
My problem is in sending bytes of file
this code send whole byte of 15Mb file but send only 20-40 kb of 2mb file
or 30-50 kb of 750 kb

I think problem is on File.ReadAllbyte()
so i used Thread.Sleep(5000)

but result is same with little change

how to force filling whole file in byte[] ?

private void StartSendingData(IPAddress ServerIP, string FileName)
{
    Socket MySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    byte[] bt = File.ReadAllBytes(FileName);
    //Thread.Sleep(5000);
    MySocket.Connect(new IPEndPoint(ServerIP, 33000));
    MySocket.Send(bt);

}

解决方案

File.ReadAllBytes should read all binary file content in the specified byte array, are you sure it doesn''t ?!?! anyway if I were you, I won''t do that ! I won''t read all the contents of the file in one byte array, specially when the file is a big file, this will make the buffer with the size of the file which is really not good.

A better way to do that is to start reading the file content in small buffer chunks of size 1k or 2k then start sending each chunk after another.


I believe the other answer was correct; ReadAllBytes should read the entire file into memory before going to the next line of code. The problem is likely with your networking code.

Check the length of the byte array after you read all the bytes. And check the value returned from the Send() method... that will be the number of bytes sent. If it doesn''t return the number of bytes loaded from the file, then you know that is where your problem is. You should also check on the receiving end of that Send() to see how many bytes are received... that could also provide some clues as to what is going on.


这篇关于读取文件字节数已完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆