C#实现FTP上传文件
时间: 2024-09-25 07:04:36 浏览: 45
在C#中,可以使用内置的System.IO命名空间下的FtpWebRequest和FtpWebResponse类来实现FTP上传文件的功能。下面是一个简单的步骤示例:
```csharp
using System;
using System.IO;
using System.Net;
public static void UploadFileToFtp(string ftpServer, string userName, string password, string filePath, string remoteDirectory)
{
try
{
// 创建FTP请求
FtpWebRequest request = (FtpWebRequest)WebRequest.Create($"ftp://{ftpServer}/{remoteDirectory}/{Path.GetFileName(filePath)}");
// 设置请求方法为PUT(用于上传)
request.Method = WebRequestMethods.Ftp.UploadFile;
// 设置基本身份验证
request.Credentials = new NetworkCredential(userName, password);
// 添加文件内容
using (FileStream fileStream = File.OpenRead(filePath))
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
request.InputStream.Write(buffer, 0, bytesRead);
}
}
// 发送请求并获取响应
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine($"上传文件成功。状态码:{response.StatusCode}");
}
}
catch (Exception ex)
{
Console.WriteLine($"上传文件失败: {ex.Message}");
}
}
// 调用函数并传入相关参数
UploadFileToFtp("your_ftp_server", "your_username", "your_password", @"C:\path\to\file.txt", "remote_directory");
```
阅读全文