c# - 使用 NetworkStream 传输文件

标签 c# .net .net-3.5 c#-3.0 networkstream

我在将文件从服务器程序传输到客户端时遇到问题。我想解决几个问题。首先,我将字节数组设置为 6000 字节大,并且始终是这个大小。有没有办法保持正确的文件大小?而且按照现在的代码方式,程序会挂起。当我将它从客户端的 while 循环中取出时它就起作用了。帮助!!

客户:

 private void button1_Click(object sender, EventArgs e)
    {   
        BinaryWriter binWriter; 
        int i = -1;
        Byte[] bytes = new Byte[6000];

        NetworkStream clientStream = connTemp.GetStream();
        byte[] outstream = Encoding.ASCII.GetBytes(txtMessage.Text);
        clientStream.Write(outstream, 0, outstream.Length);


        while (i != 0)
        {
            try
            {
                if (clientStream.CanRead)
                {
                    i = clientStream.Read(bytes, 0, bytes.Length);

                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                break;
            }
        }


        binWriter = new BinaryWriter(File.Open("C:\\SeanLaunch\\log.rxlog",FileMode.Create));
        binWriter.Write(bytes);
        binWriter.Close();

    }

}

服务器:

  Byte[] fileToSendAsByteArray = new Byte[6000];
  fileToSendAsByteArray = File.ReadAllBytes("C:\\Launch\\Test.rxlog");
  stream.Write(fileToSendAsByteArray, 0, fileToSendAsByteArray.Length);

编辑!!!:我修复了循环问题。

最佳答案

一个问题是,即使您只从文件中读取一个字节,您也会将整个 6000 字节写入流中。

使用 FileStream访问文件并将内容复制到 NetworkStream。 Framework 4.0对此有一个很好的功能

FileStream fs = new FileStream(...);
fs.CopyTo(stream);

您可以在客户端采取类似的方法,只是相反,从 NetworkStream 复制到目标 Stream。

在 Framework 4.0 之前,您可以实现自己的 CopyTo 函数。像这样的事情

public static long CopyStream(Stream source, Stream target)
{
  const int bufSize = 0x1000;
  byte[] buf = new byte[bufSize];

  long totalBytes = 0;
  int bytesRead = 0;

  while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
  {
    target.Write(buf, 0, bytesRead);
    totalBytes += bytesRead;
  }
  return totalBytes;
}

关于c# - 使用 NetworkStream 传输文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3663369/

相关文章:

c# - 在winform的ReportViewer的LocalReport中导出为CSV

c# - 在数据集 C# 中查询

.net - 如何使用dotnet仅对jpg文件中的图像数据进行哈希处理?

c# - 针对 .NET Framework 3.5 编译的项目允许 C# 4.0 功能

c# - 如何获得具有多个类型参数的泛型类的类型? - C#

c# - 在 dll 而不是主应用程序中查找资源

c# - 工厂模式应该放在 DDD 中的什么位置?

c# - 对象的 GetType 正在返回 RuntimeType

c# - Visual Studio 2008 无法识别 Lambda 表达式语法

ajax - 引用的 .dll 中抛出异常如何调试?