C# ftp上传帮助类
时间: 2023-08-03 07:37:50 浏览: 48
以下是一个基于C#的FTP上传帮助类示例:
```csharp
using System;
using System.IO;
using System.Net;
public class FtpHelper
{
private string ftpServerIP;
private string ftpUserID;
private string ftpPassword;
private FtpWebRequest reqFTP;
public FtpHelper(string ftpServerIP, string ftpUserID, string ftpPassword)
{
this.ftpServerIP = ftpServerIP;
this.ftpUserID = ftpUserID;
this.ftpPassword = ftpPassword;
}
// 上传文件
public bool Upload(string localFilePath, string remoteFileName)
{
FileInfo fileInfo = new FileInfo(localFilePath);
string uri = "ftp://" + ftpServerIP + "/" + remoteFileName;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInfo.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
using (FileStream fs = fileInfo.OpenRead())
{
using (Stream strm = reqFTP.GetRequestStream())
{
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
}
}
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
response.Close();
return true;
}
}
```
使用方法:
```csharp
string localFilePath = @"C:\test.txt";
string remoteFileName = "test.txt";
string ftpServerIP = "ftp://192.168.1.1";
string ftpUserID = "username";
string ftpPassword = "password";
FtpHelper ftpHelper = new FtpHelper(ftpServerIP, ftpUserID, ftpPassword);
ftpHelper.Upload(localFilePath, remoteFileName);
```
其中,`localFilePath`为本地文件路径,`remoteFileName`为远程文件名,`ftpServerIP`为FTP服务器地址,`ftpUserID`和`ftpPassword`为FTP登录凭据。