Use asp.net FtpWebRequest to implement common FTP Functions

Source: Internet
Author: User

The following code uses. net FtpWebRequest to implement common FTP functions. The Code has been debugged and can be copied and used directly. It is tested that FTP operations implemented in this way and FTP operations using commands are much more stable. Correct the design.

 

Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. IO;
Using System. Net;
Using System. Windows. Forms;
Using System. Globalization;

Namespace FtpTest1
{

Public class FtpWeb
{
String ftpServerIP;
String ftpRemotePath;
String ftpUserID;
String ftpPassword;
String ftpURI;

/// <Summary>
/// Connect to FTP
/// </Summary>
/// <Param name = "FtpServerIP"> FTP connection address </param>
/// <Param name = "FtpRemotePath"> specifies the current directory after successful FTP connection. If this parameter is not specified, it is the root directory by default. </param>
/// <Param name = "FtpUserID"> User name </param>
/// <Param name = "FtpPassword"> password </param>
Public FtpWeb (string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
{
FtpServerIP = FtpServerIP;
FtpRemotePath = FtpRemotePath;
FtpUserID = FtpUserID;
FtpPassword = FtpPassword;
FtpURI = "ftp: //" + ftpServerIP + "/" + ftpRemotePath + "/";
}

/// <Summary>
/// Upload
/// </Summary>
/// <Param name = "filename"> </param>
Public void Upload (string filename)
{
FileInfo fileInf = new FileInfo (filename );
String uri = ftpURI + fileInf. Name;
FtpWebRequest reqFTP;

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 = fileInf. Length;
Int buffLength = 2048;
Byte [] buff = new byte [buffLength];
Int contentLen;
FileStream fs = fileInf. OpenRead ();
Try
{
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 ();
Fs. Close ();
}
Catch (Exception ex)
{
Insert_Standard_ErrorLog.Insert ("FtpWeb", "Upload Error -->" + ex. Message );
}
}

/// <Summary>
/// Download
/// </Summary>
/// <Param name = "filePath"> </param>
/// <Param name = "fileName"> </param>
Public void Download (string filePath, string fileName)
{
FtpWebRequest reqFTP;
Try
{
FileStream outputStream = new FileStream (filePath + "\" + fileName, FileMode. Create );

ReqFTP = (FtpWebRequest) FtpWebRequest. Create (new Uri (ftpURI + fileName ));
ReqFTP. Method = WebRequestMethods. Ftp. DownloadFile;
ReqFTP. UseBinary = true;
ReqFTP. Credentials = new NetworkCredential (ftpUserID, ftpPassword );
FtpWebResponse response = (FtpWebResponse) reqFTP. GetResponse ();
Stream ftpStream = response. GetResponseStream ();

Long cl = response. ContentLength;

Int buffer size = 2048;
Int readCount;
Byte [] buffer = new byte [bufferSize];

ReadCount = ftpStream. Read (buffer, 0, bufferSize );
While (readCount> 0)
{
OutputStream. Write (buffer, 0, readCount );
ReadCount = ftpStream. Read (buffer, 0, bufferSize );
}

FtpStream. Close ();
OutputStream. Close ();
Response. Close ();
}
Catch (Exception ex)
{
Insert_Standard_ErrorLog.Insert ("FtpWeb", "Download Error -->" + ex. Message );
}
}

/// <Summary>
/// Delete an object
/// </Summary>
/// <Param name = "fileName"> </param>
Public void Delete (string fileName)
{
Try
{
String uri = ftpURI + fileName;
FtpWebRequest reqFTP;
ReqFTP = (FtpWebRequest) FtpWebRequest. Create (new Uri (uri ));

ReqFTP. Credentials = new NetworkCredential (ftpUserID, ftpPassword );
ReqFTP. KeepAlive = false;
ReqFTP. Method = WebRequestMethods. Ftp. DeleteFile;

String result = String. Empty;
FtpWebResponse response = (FtpWebResponse) reqFTP. GetResponse ();
Long size = response. ContentLength;
Stream datastream = response. GetResponseStream ();
StreamReader sr = new StreamReader (datastream );
Result = sr. ReadToEnd ();
Sr. Close ();
Datastream. Close ();
Response. Close ();
}
Catch (Exception ex)
{
Insert_Standard_ErrorLog.Insert ("FtpWeb", "Delete Error -->" + ex. Message + "file name:" + fileName );
}
}

/// <Summary>
/// Obtain the details of the current directory (including files and folders)
/// </Summary>
/// <Returns> </returns>
Public string [] GetFilesDetailList ()
{
String [] downloadFiles;
Try
{
StringBuilder result = new StringBuilder ();
FtpWebRequest ftp;
Ftp = (FtpWebRequest) FtpWebRequest. Create (new Uri (ftpURI ));
Ftp. Credentials = new NetworkCredential (ftpUserID, ftpPassword );
Ftp. Method = WebRequestMethods. Ftp. ListDirectoryDetails;
WebResponse response = ftp. GetResponse ();
StreamReader reader = new StreamReader (response. GetResponseStream ());
String line = reader. ReadLine ();
Line = reader. ReadLine ();
Line = reader. ReadLine ();
While (line! = Null)
{
Result. Append (line );
Result. Append ("\ n ");

Result. Remove (result. ToString (). LastIndexOf ("\ n"), 1 );
Reader. Close ();
Response. Close ();
Return result. ToString (). Split ('\ n ');
}
Catch (Exception ex)
{
DownloadFiles = null;
Insert_Standard_ErrorLog.Insert ("FtpWeb", "GetFilesDetailList Error -->" + ex. Message );
Return downloadFiles;
}
}

/// <Summary>
/// Obtain the list of objects in the current directory (only files)
/// </Summary>
/// <Returns> </returns>
Public string [] GetFileList (string mask)
{
String [] downloadFiles;
StringBuilder result = new StringBuilder ();
FtpWebRequest reqFTP;
Try
{
ReqFTP = (FtpWebRequest) FtpWebRequest. Create (new Uri (ftpURI ));
ReqFTP. UseBinary = true;
ReqFTP. Credentials = new NetworkCredential (ftpUserID, ftpPassword );
ReqFTP. Method = WebRequestMethods. Ftp. ListDirectory;
WebResponse response = reqFTP. GetResponse ();
StreamReader reader = new StreamReader (response. GetResponseStream ());

String line = reader. ReadLine ();
While (line! = Null)
{
If (mask. Trim ()! = String. Empty & mask. Trim ()! = "*.*")
{
String mask _ = mask. Substring (0, mask. IndexOf ("*"));
If (line. Substring (0, mask _. Length) = mask _)
{
Result. Append (line );
Result. Append ("\ n ");
}
}
Else
{
Result. Append (line );
Result. Append ("\ n ");
}
Line = reader. ReadLine ();
}
Result. Remove (result. ToString (). LastIndexOf ('\ n'), 1 );
Reader. Close ();
Response. Close ();
Return result. ToString (). Split ('\ n ');
}
Catch (Exception ex)
{
DownloadFiles = null;
If (ex. Message. Trim ()! = "Remote server return error: (550) the file is unavailable (for example, the file is not found and the file cannot be accessed ). ")
{
Insert_Standard_ErrorLog.Insert ("FtpWeb", "GetFileList Error -->" + ex. Message. ToString ());
}
Return downloadFiles;
}
}

/// <Summary>
/// Obtain the list of all folders in the current directory (Only folders)
/// </Summary>
& Nbsp; // <returns> </returns>
Public string [] GetDirectoryList ()
{
String [] drectory = GetFilesDetailList ();
String m = string. Empty;
Foreach (string str in drectory)
{
If (str. Trim (). Substring (0, 1). ToUpper () = "D ")
{
M + = str. Substring (54). Trim () + "\ n ";
}
}

Char [] n = new char [] {'\ n '};
Return m. Split (n );
}
 
/// <Summary>
/// Determine whether the specified subdirectory in the current directory exists
/// </Summary>
/// <Param name = "RemoteDirectoryName"> specified directory name </param>
Public bool DirectoryExist (string RemoteDirectoryName)
{
String [] dirList = GetDirectoryList ();
Foreach (string str in dirList)
{
If (str. Trim () = RemoteDirectoryName. Trim ())
{
Return true;
}
}
Return false;
}

/// <Summary>
/// Determine whether the specified file in the current directory exists
/// </Summary>
/// <Param name = "RemoteFileName"> remote file name </param>
Public bool FileExist (string RemoteFileName)
{
String [] fileList = GetFileList ("*.*");
Foreach (string str in fileList)
{
If (str. Trim () = RemoteFileName. Trim ())
{
Return true;
}
}
Return false;
}

/// <Summary>
/// Create a folder
/// </Summary>
/// <Param name = "dirName"> </param>
Public void MakeDir (string dirName)
{
FtpWebRequest reqFTP;
Try
{
// DirName = name of the directory to create.
ReqFTP = (FtpWebRequest) FtpWebRequest. Create (new Uri (ftpURI + dirName ));
ReqFTP. Method = WebRequestMethods. Ftp. MakeDirectory;
ReqFTP. UseBinary = true;
ReqFTP. Credentials = new NetworkCredential (ftpUserID, ftpPassword );
FtpWebResponse response = (FtpWebResponse) reqFTP. GetResponse ();
Stream ftpStream = response. GetResponseStream ();

FtpStream. Close ();
Response. Close ();
}
Catch (Exception ex)
{
Insert_Standard_ErrorLog.Insert ("FtpWeb", "MakeDir Error -->" + ex. Message );
}
}

/// <Summary>
/// Obtain the specified file size
/// </Summary>
/// <Param name = "filename"> </param>
/// <Returns> </returns>
Public long GetFileSize (string filename)
{
FtpWebRequest reqFTP;
Long fileSize = 0;
Try
{
ReqFTP = (FtpWebRequest) FtpWebRequest. Create (new Uri (ftpURI + filename ));
ReqFTP. Method = WebRequestMethods. Ftp. GetFileSize;

 

; ReqFTP. UseBinary = true;
ReqFTP. Credentials = new NetworkCredential (ftpUserID, ftpPassword );
FtpWebResponse response = (FtpWebResponse) reqFTP. GetResponse ();
Stream ftpStream = response. GetResponseStream ();
FileSize = response. ContentLength;

FtpStream. Close ();
Response. Close ();
}
Catch (Exception ex)
{
Insert_Standard_ErrorLog.Insert ("FtpWeb", "GetFileSize Error -->" + ex. Message );
}
Return fileSize;
}

/// <Summary>
/// Rename
/// </Summary>
/// <Param name = "currentFilename"> </param>
/// <Param name = "newFilename"> </param>
Public void ReName (string currentFilename, string newFilename)
{
FtpWebRequest reqFTP;
Try
{
ReqFTP = (FtpWebRequest) FtpWebRequest. Create (new Uri (ftpURI + currentFilename ));
ReqFTP. Method = WebRequestMethods. Ftp. Rename;
ReqFTP. RenameTo = newFilename;
ReqFTP. UseBinary = true;
ReqFTP. Credentials = new NetworkCredential (ftpUserID, ftpPassword );
FtpWebResponse response = (FtpWebResponse) reqFTP. GetResponse ();
Stream ftpStream = response. GetResponseStream ();

FtpStream. Close ();
Response. Close ();
}
Catch (Exception ex)
{
Insert_Standard_ErrorLog.Insert ("FtpWeb", "ReName Error -->" + ex. Message );
}
}

/// <Summary>
/// Move the file
/// </Summary>
/// <Param name = "currentFilename"> </param>
/// <Param name = "newFilename"> </param>
Public void MovieFile (string currentFilename, string newDirectory)
{
ReName (currentFilename, newDirectory );
}

/// <Summary>
/// Switch the current directory
/// </Summary>
/// <Param name = "DirectoryName"> </param>
/// <Param name = "IsRoot"> true absolute path false relative path </param>
Public void GotoDirectory (string DirectoryName, bool IsRoot)
{
If (IsRoot)
{
FtpRemotePath = DirectoryName;
}
Else
{
FtpRemotePath + = DirectoryName + "/";
}
FtpURI = "ftp: //" + ftpServerIP + "/" + ftpRemotePath + "/";
}

}

Public class Insert_Standard_ErrorLog
{
Public static void Insert (string x, string y)
{

}
}

}

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.