我试图为客户端创建一种从服务器请求文件或文件夹并将其保存到文档中的方法。所以目前我有所有服务器文件的树形视图,客户端可以右键单击并接收包含以下代码的文件或文件夹:
if (isConnected())
{
if (selectedFile.Nodes.Count > 0) //If its a folder
{
consoleLog("Receiving folder (" + selectedFile.Text + ")... please wait");
clientSendText("receiveFolder#" + selectedFile.FullPath.ToString() + "#", 1);
}
else //If its a file
{
consoleLog("Receiving file (" + selectedFile.Text + ")... please wait");
clientSendText("receiveFile#" + selectedFile.FullPath.ToString() + "#", 1);
}
}
所以发送命令接收文件或文件夹,然后服务器端它将运行以下命令之一,具体取决于它是文件还是文件夹
public static void receiveFolder(string path)
{
path = getFullFolderPath(path);
if (Directory.Exists(path))
{
ZipFile.CreateFromDirectory(path, path + ".zip", CompressionLevel.Fastest, true);
serverSendFile(path + ".zip", 8);
if (File.Exists(path + ".zip"))
{
File.Delete(path + ".zip");
}
}
else
{
serverSendText("Folder does not exist", 1);
}
}
public static void receiveFile(string path)
{
path = getFullFilePath(path);
if (File.Exists(path))
{
serverSendFile(path, 9);
}
else
{
serverSendText("File does not exist", 1);
}
}
所以我发送文件夹的方式是先将其压缩,然后将其作为文件发送,然后删除zip文件夹。
注意第二个参数是数据类型,因此8是zip,9是任何文件 客户端接收它如下:
else if (dataType == 8)
{
this.Invoke(new MethodInvoker(delegate
{
string savePath = Properties.Settings.Default.textSavePath;
consoleLog("Reply from server: folder receiving...please wait");
File.WriteAllBytes(savePath + ".zip", data);
ZipFile.ExtractToDirectory(savePath + ".zip", savePath);
if (File.Exists(savePath + ".zip"))
{
File.Delete(savePath + ".zip");
}
consoleLog("Folder saved to " + savePath);
}));
}
else if (dataType == 9)
{
this.Invoke(new MethodInvoker(delegate
{
string savePath = Properties.Settings.Default.textSavePath;
consoleLog("Reply from server: file receiving...please wait");
File.WriteAllBytes(savePath, data);
consoleLog("File saved to " + savePath);
}));
}
因此,接收文件夹工作正常,默认保存位置是mydocuments,所以它发送具有相同名称,解压缩自己,我可以像平常一样查看它。它与普通文件相同,除了它没有文件名,我必须手动添加" /picture.png"保存路径的末尾,以便它保存,当它保存完美,图像完好无损,但我不知道为什么文件夹保持其名称,但文件不。文件名是否与数据一起发送?我在我面前遗漏了什么,任何建议都会对你有所帮助
我也使用下面的代码发送文件
public static void serverSendFile(string filePath, byte dataType)
{
if (tcpServer != null)
{
if (tcpClient.Connected == true)
{
byte[] data = File.ReadAllBytes(filePath);
data = data.Concat(new byte[] { (byte)dataType }).ToArray();
stream = tcpClient.GetStream();
int length = data.Length;
byte[] datalength = new byte[4];
datalength = BitConverter.GetBytes(length);
stream.Write(datalength, 0, 4);
stream.Write(data, 0, data.Length);
}
}
}
答案 0 :(得分:0)
当您收到一个zip文件时,请将其保存在名称" .zip"然后提取它。 Zip文件包含有关文件和文件夹名称的信息。
当您收到其他文件时,您无法处理有关文件名的任何信息(您是否将其与内容一起发送?)
您需要组合savePath和文件名,并将数据写入此文件。