C#发送文件到ftp
时间: 2023-08-16 19:04:50 浏览: 161
你可以使用C#中的`System.Net`命名空间下的`FtpWebRequest`和`FtpWebResponse`类来发送文件到FTP服务器。下面是一个简单的示例代码:
```csharp
using System;
using System.IO;
using System.Net;
class Program
{
static void Main()
{
string ftpServer = "ftp://ftp.example.com";
string ftpUsername = "username";
string ftpPassword = "password";
string localFilePath = "local_file_path";
string remoteFilePath = "remote_file_path";
// 创建一个 FTP 请求对象
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + "/" + remoteFilePath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
// 读取本地文件数据
byte[] fileContents;
using (StreamReader sourceStream = new StreamReader(localFilePath))
{
fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
}
// 将文件数据写入 FTP 请求流
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
// 获取 FTP 响应
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("上传完成,状态:" + response.StatusDescription);
// 关闭 FTP 响应
response.Close();
}
}
```
在示例代码中,你需要替换以下变量的值:
- `ftpServer`: FTP服务器的地址
- `ftpUsername`: FTP服务器的用户名
- `ftpPassword`: FTP服务器的密码
- `localFilePath`: 本地文件的路径
- `remoteFilePath`: 上传到FTP服务器的文件路径
这个示例代码会将本地文件上传到指定的FTP服务器上。请确保你的应用程序具有足够的权限来访问和上传文件到FTP服务器。
阅读全文
相关推荐















