我正在尝试使用C#类NetworkStream传输数据库,但每次转换不同的字节数。 即使数据库很小(388KB),也只有一部分传递给客户端。 传递一个小文本文件没有问题。
服务器:
NetworkStream netStream = client.GetStream(); byte[] file = File.ReadAllBytes(Directory.GetCurrentDirectory() + "\\viruses_database.accdb"); netStream.Write(file, 0, file.Length);客户:
NetworkStream netStream=client.GetStream(); Stream stream = new FileStream(Directory.GetCurrentDirectory() + "\\viruses_database.accdb", FileMode.Create, FileAccess.ReadWrite); Byte[] bytes = new Byte[1024]; int length=bytes.Length; int cnt = 0; while (netStream.CanRead && length==bytes.Length) { length = netStream.Read(bytes, 0, bytes.Length); stream.Write(bytes, 0, bytes.Length); cnt++; } stream.Close();我怀疑问题在于转移不是异步完成的
I'm trying to transfer a database using the C# class NetworkStream, but every time a different amount of bytes is transformed. even though the database is minimal (388KB), only a part of it passes to the client. a small text file is passed without problems.
server:
NetworkStream netStream = client.GetStream(); byte[] file = File.ReadAllBytes(Directory.GetCurrentDirectory() + "\\viruses_database.accdb"); netStream.Write(file, 0, file.Length);client:
NetworkStream netStream=client.GetStream(); Stream stream = new FileStream(Directory.GetCurrentDirectory() + "\\viruses_database.accdb", FileMode.Create, FileAccess.ReadWrite); Byte[] bytes = new Byte[1024]; int length=bytes.Length; int cnt = 0; while (netStream.CanRead && length==bytes.Length) { length = netStream.Read(bytes, 0, bytes.Length); stream.Write(bytes, 0, bytes.Length); cnt++; } stream.Close();I suspect that the problem lies in the fact that the transfering isn't done asynchronously
最满意答案
stream.Write(bytes, 0, bytes.Length);这是一个错误。 您只收到长度字节,但您正在写入1024字节。 这将任意破坏文件中的数据并使其最终大小不可预测。 固定:
stream.Write(bytes, 0, length);支持CopyTo()方法(自.NET 4以来可用)以避免这样的错误:
using (var input = client.GetStream()) using (var output = new FileStream(path, FileMode.Create, FileAccess.Write)) { input.CopyTo(output); }Directory.GetCurrentDirectory()是另一个错误,它太难以预测了,当你的程序安装在用户的机器上时,很少能写入它。 数据文件属于appdata目录,使用Environment.GetFolderPath()
stream.Write(bytes, 0, bytes.Length);That's a bug. You only received length bytes but you are writing 1024 bytes. This will arbitrarily corrupt the data in the file and make its final size unpredictable. Fix:
stream.Write(bytes, 0, length);Do favor the CopyTo() method (available since .NET 4) to avoid bugs like this:
using (var input = client.GetStream()) using (var output = new FileStream(path, FileMode.Create, FileAccess.Write)) { input.CopyTo(output); }Directory.GetCurrentDirectory() is another bug, it is too unpredictable and you rarely can write to it when your program is installed on the user's machine. Data files belong in the appdata directory, use Environment.GetFolderPath()
更多推荐
发布评论