本文介绍了如何将文件夹及其内容(子文件夹/文件)发送到服务器客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在制作文件传输(服务器-客户端)应用程序。即时通讯使用TCP。 (.net 4.0)
I'm making a file transfer (server-client) application. im using TCP. (.net 4.0)
如何将包含所有内容(文件夹/文件)的文件夹发送到另一端?
How do I send a Folder with all its contents(folder/files) to the other side ??
我有以下方法可以正常工作:
I have these methods that works fine:
Send(string srcPath, string destPath) //sends a single file
Recieve(string destPath) //recieves a single file
这是Send方法:
public void Send(string srcPath, string destPath)
{
using (fs = new FileStream(srcPath, FileMode.Open, FileAccess.Read))
{
try
{
fileSize = fs.Length;
while (sum < fileSize)
{
if (fileSize - sum < packetSize)
{
count = fs.Read(data, 0, (int)(fileSize - sum));
network.Write(data, 0, (int)(fileSize - sum));
}
else
{
count = fs.Read(data, 0, data.Length);
network.Write(data, 0, data.Length);
}
fs.Seek(sum, SeekOrigin.Begin);
sum += count;
}
network.Flush();
}
finally
{
fs.Dispose();
}
}
}
这是接收方法:
public void Recieve(string destPath)
{
using (fs = new FileStream(destPath, FileMode.Create, FileAccess.Write))
{
try
{
while (sum < fileSize)
{
if (fileSize - sum < packetSize)
{
count = network.Read(data, 0, (int)(fileSize - sum));
fs.Write(data, 0, (int)(fileSize - sum));
}
else
{
count = network.Read(data, 0, data.Length);
fs.Write(data, 0, data.Length);
}
fs.Seek(sum, SeekOrigin.Begin);
sum += count;
}
}
finally
{
fs.Dispose();
}
}
}
这是一个常见变量:
const int packetSize = 1024 * 8; //Packet Size.
long sum; //Sum of sent data.
long fileSize; //File Size.
int count = 0; //data counter.
static byte[] data = null; //data buffer.
NetworkStream network;
FileStream fs;
我也得到:
bool IsFolder(string path) //that returns if the path is a folder or a file
推荐答案
我已经弄清楚答案了
I've figured out the answer
public void SendFolder(string srcPath, string destPath)
{
string dirName = Path.Combine(destPath, Path.GetFileName(srcPath));
CreateDirectory(dirName); // consider that this method creates a directory at the server
string[] fileEntries = Directory.GetFiles(srcPath);
string[] subDirEntries = Directory.GetDirectories(srcPath);
foreach (string filePath in fileEntries)
{
Send(srcPath, dirName);
}
foreach (string dirPath in subDirEntries)
{
SendFolder(dirPath, dirName);
}
}
服务器将首先创建一个目录库。从客户端使用目录的相同名称.. dirName
the server will first create a direcotory .. named the same name of the directory from the client side .. which is dirName
然后它将发送该文件夹中的所有文件..
然后它将递归执行每个文件夹都一样..问题解决了
then it will send all the files in that folder ..then it will recursively do the same for each folder .. problem solved
这篇关于如何将文件夹及其内容(子文件夹/文件)发送到服务器客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!