C#使用ftp上传图片
时间: 2025-04-28 07:25:50 浏览: 15
### C# 使用 FTP 上传图片
为了实现通过 FTP 协议上传图片的功能,可以利用 `System.Net` 命名空间中的类来完成操作。下面是一个完整的例子,展示了如何使用 C# 将本地文件作为二进制流发送到指定的 FTP 地址。
```csharp
using System;
using System.IO;
using System.Net;
public class FtpUploader {
public static void UploadFileToFtp(string filePath, string ftpServerUrl, string username = "", string password = "") {
try {
FileInfo fileInfo = new FileInfo(filePath);
// 创建请求对象并设置属性
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServerUrl + "/" + fileInfo.Name);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
// 设置缓冲区大小为2KB
int bufferLength = 2048;
byte[] bufffer = new byte[bufferLength];
// 打开读取本地文件以及写入远程服务器的数据流
using FileStream fs = File.OpenRead(filePath);
using Stream rs = request.GetRequestStream();
int contentLength;
do {
contentLength = fs.Read(bufffer, 0, bufferLength);
rs.Write(bufffer, 0, contentLength);
} while (contentLength != 0);
Console.WriteLine($"成功上传 {fileInfo.FullName} 至 {ftpServerUrl}");
}
catch (WebException ex) when (((FtpWebResponse)ex.Response).StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) {
Console.WriteLine("无法找到要上传的文件");
}
catch (Exception e) {
Console.WriteLine(e.Message);
}
}
}
```
此代码片段定义了一个名为 `UploadFileToFtp` 的静态方法,该方法接收四个参数:待上传文件路径 (`filePath`)、目标 FTP URL (`ftpServerUrl`) 和可选的身份验证凭证 (`username`, `password`). 方法内部创建了指向 FTP 资源位置的新连接,并将选定文件的内容逐块传输至远端存储器上[^1].
#### 注意事项:
- 如果 FTP 需要身份认证,则需提供有效的用户名和密码。
- 对于某些特定环境下的 FTP 服务可能还需要额外配置 SSL/TLS 加密选项或其他安全措施。
- 当处理大文件时建议增加超时时间以防止因网络延迟造成异常中断。
阅读全文
相关推荐
















