我正在制作文件传输(服务器 - 客户端)应用程序。即时通讯使用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
答案 0 :(得分:1)
使用目录路径可以执行此操作:
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);
}
}
}
答案 1 :(得分:1)
我已经找到答案了
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);
}
}
服务器将首先创建一个direkory ..从客户端命名相同的目录名称..这是dirName
然后它将发送该文件夹中的所有文件.. 然后它将递归地为每个文件夹执行相同的操作..问题已解决