在C#中,可以使用Socket類來實現文件上傳和下載。以下是一個簡單的示例代碼,用于實現文件上傳和下載功能:
文件上傳:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
class FileUploadClient
{
static void Main()
{
string filePath = "path/to/file.txt";
string serverIp = "127.0.0.1";
int serverPort = 8888;
// 讀取文件內容
byte[] fileData = File.ReadAllBytes(filePath);
// 連接服務器
TcpClient client = new TcpClient(serverIp, serverPort);
NetworkStream stream = client.GetStream();
// 發送文件內容
stream.Write(fileData, 0, fileData.Length);
Console.WriteLine("File uploaded successfully");
// 關閉連接
stream.Close();
client.Close();
}
}
文件下載:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
class FileDownloadClient
{
static void Main()
{
string filePath = "path/to/save/file.txt";
string serverIp = "127.0.0.1";
int serverPort = 8888;
// 連接服務器
TcpClient client = new TcpClient(serverIp, serverPort);
NetworkStream stream = client.GetStream();
// 接收文件內容
byte[] buffer = new byte[1024];
int bytesRead;
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, bytesRead);
}
}
Console.WriteLine("File downloaded successfully");
// 關閉連接
stream.Close();
client.Close();
}
}
在以上示例中,FileUploadClient用于上傳文件到服務器,FileDownloadClient用于從服務器下載文件。在上傳文件時,先讀取文件內容,然后通過TcpClient和NetworkStream來發送文件內容到服務器。在下載文件時,創建一個FileStream來保存接收到的文件內容。最后關閉連接并輸出操作成功的消息。