/// <summary>
/// FTP上传文件
/// </summary>
class FTPUpFile
{//string Filetype = ConfigurationManager.AppSettings["FileType"];没有该包,报错注释
//string ipaddress = ConfigurationManager.AppSettings["IPaddress"];没有该包,报错注释
//string Username = ConfigurationManager.AppSettings["UserName"];没有该包,报错注释
//string Password = ConfigurationManager.AppSettings["Password"];没有该包,报错注释
/// <summary>
/// FTP上传文件
/// </summary>
/// <param name="filename">上传文件路径</param>
/// <param name="ftpServerIP">FTP服务器的IP和端口</param>
/// <param name="ftpPath">FTP服务器下的哪个目录</param>
/// <param name="ftpUserID">FTP用户名</param>
/// <param name="ftpPassword">FTP密码</param>
public static bool Upload(string filename, string ftpServerIP, string ftpPath, string ftpUserID, string ftpPassword)
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpServerIP + "/" + ftpPath + "/" + fileInf.Name;
string ftpPathN = "ftp://" + ftpServerIP + "/" + ftpPath;
string dirNameN = fileInf.Name;
//bool fa = CheckDirectoryExist(ftpPathN,dirNameN,ftpUserID,ftpPassword);
try
{
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// 指定数据传输类型
reqFTP.UseBinary = true;
// 上传文件时通知服务器文件的大小
reqFTP.ContentLength = fileInf.Length;
//this.Invoke(InitUProgress, fileInf.Length);
// 缓冲大小设置为2kb
int buffLength = 4096;
byte[] buff = new byte[buffLength];
int contentLen;
// 打开一个文件流 (System.IO.FileStream) 去读上传的文件
FileStream fs = fileInf.OpenRead();
// 把上传的文件写入流
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// 关闭两个流
strm.Close();
strm.Dispose();
fs.Close();
fs.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 重命名
/// </summary>
/// <param name="ftpPath">ftp文件路径</param>
/// <param name="currentFilename"></param>
/// <param name="newFilename"></param>
public static bool fileRename(string ftpServerIP, string ftpPath, string currentFileName, string newFileName, string ftpUser, string ftpPassword)
{
bool success = false;
FtpWebRequest ftpWebRequest = null;
FtpWebResponse ftpWebResponse = null;
Stream ftpResponseStream = null;
try
{
string uri = "ftp://" + ftpServerIP + "/" + ftpPath + "/" + currentFileName;
ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
ftpWebRequest.UseBinary = true;
ftpWebRequest.Method = WebRequestMethods.Ftp.Rename;
ftpWebRequest.RenameTo = newFileName;
ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
ftpResponseStream = ftpWebResponse.GetResponseStream();
success = true;
C#FTPUpFile公共类
![](https://img-home.csdnimg.cn/images/20240711042549.png)