c# - 为什么 File.WriteAllBytes 不适用于 .db 文件但适用于 .csv 文件?
问题描述
我正在尝试将表示完整文件的 Byte[] 数组写入文件。此文件可能具有.csv或.db扩展名。
我已经建立了一个基于 MSDN Synchronous Sockets 的同步客户端和服务器应用程序
通过 SO 搜索后,我发现了这个(Can a Byte[] Array be write to a file in C#?)帖子,这似乎表明可以使用以下方法将字节数组写入文件:
File.WriteAllBytes(string path, byte[] bytes)
我的问题是这种方法似乎适用于 .csv 文件,但不适用于 .db 文件。
为什么会这样?
下面的一些代码。
//Client-side
public static void StartClient()
{
byte[] bytes = new byte[9000];
try
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
Socket sender = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
sender.Connect(remoteEP);
byte[] msg= File.ReadAllBytes("CsvOrDbPath");
int bytesSent = sender.Send(msg);
int bytesRec = sender.Receive(bytes);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se) {
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
//Server-side
public static string data = null;
public static void StartListening()
{
byte[] bytes = new byte[9000];
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
Socket handler = listener.Accept();
data = null;
while (true)
{
int bytesRec = handler.Receive(bytes);
int expecting = 8; //expected number of bytes
string path = "CSVorDbPath";
// Need to encode back into .db file format somehow
// Works for csv
File.WriteAllBytes(path, bytes);
break;
}
//Echo the data back to the client.
//byte[] msg = Encoding.ASCII.GetBytes(data);
//handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
当我使用 .csv 文件时,此过程在一定程度上有效,并且我在我的服务器计算机上收到了相同的文件。当我使用 .db 文件时,该过程会生成 .db 文件,但它无法打开。
我怀疑问题是由于我没有将 .db 数据编码为适当的格式 - 请有人解释发生了什么?
解决方案
您正在将整个 9000 字节缓冲区写入文件。如果接收到的文件小于这个值,则意味着在磁盘上的文件中也写入了一堆 0 字节。打开 CSV 文件的软件可能不关心并丢弃那些额外的数据,但 db 格式的软件可能更严格。
尝试仅将接收到的字节数写入文件,例如使用 Linq:
File.WriteAllBytes(path, bytes.Take(bytesRec).ToArray());
推荐阅读
- user-interface - 最好的 Gui 编译语言?
- reactjs - React.js 未连接到 EC2 上的 (localhost) Ganache:ERR_CONNECTION_REFUSED 127.0.0.1:8545
- pycharm - 如何在 PyCharm 评论中添加删除线?
- api - 请求 - Google Maps Javascript API
- r - 计算动态列数中的行匹配数
- c# - SSH.NET [ObjectDisposedException:无法访问已处置的对象。对象名称:'Renci.SshNet.SshClient'。]
- r - R:使用 R 中的 cph(rms 包)对 cox 模型的连续变量和分类变量进行交互样条分析
- java - Jacoco - 如何检查哪些行缺少覆盖
- python - Pandas 根据其他列中的值创建新列
- flutter - 使用会话令牌限制 Flutter 中的国家和引用