如何将文件夹及其内容(子文件夹/文件)发送到服务器客户端
本文关键字:文件夹 文件 客户端 服务器 | 更新日期: 2023-09-27 18:26:11
我正在制作一个文件传输(服务器-客户端)应用程序。im使用TCP。(.net 4.0)
如何将文件夹及其所有内容(文件夹/文件)发送到另一侧??
我有这些方法可以很好地工作:
Send(string srcPath, string destPath) //sends a single file
Recieve(string destPath) //recieves a single file
这是发送方法:
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
使用目录路径可以做到这一点:
public void SendAll(string DirectoryPath)
{
if (Directory.Exists(DirectoryPath))
{
string[] fileEntries = Directory.GetFiles(DirectoryPath);
string[] subdirEntries = Directory.GetDirectories(DirectoryPath);
foreach (string fileName in fileEntries)
{
Send(fileName);
}
foreach (string dirName in subdirEntries)
{
SendAll(dirName);
}
}
}
我已经找到了答案
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
然后它将发送该文件夹中的所有文件。。那么它将递归地对每个文件夹执行相同的操作。。问题已解决