阅读量:0
在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来保存接收到的文件内容。最后关闭连接并输出操作成功的消息。