我正在尝试将表示完整文件的 Byte[] 数组写入文件。 此文件可能具有 .csv 或 .db 扩展名。
我已经建立了一个基于 MSDN 同步套接字的同步客户端和服务器应用程序
通过 S.O 搜索后,我发现了这个 ( Can a Byte[] Array be written 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());
关于c# - 为什么 File.WriteAllBytes 不适用于 .db 文件但适用于 .csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58112932/