我在将文件从服务器程序传输到客户端时遇到问题。我想解决几个问题。首先,我将字节数组设置为 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/