📄 ftpclient.cs
字号:
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Sockets;
using System.Diagnostics;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
/*
* FTP Client library in C#
* Author: Jaimon Mathew
* mailto:jaimonmathew@rediffmail.com
* http://www.csharphelp.com/archives/archive9.html
*
* Addapted for use by Dan Glass 07/03/03
*/
namespace WebCamService
{
public class FtpClient
{
public class FtpException : Exception
{
public FtpException(string message) : base(message){}
public FtpException(string message, Exception innerException) : base(message,innerException){}
}
private static int BUFFER_SIZE = 512;
private static Encoding ASCII = Encoding.ASCII;
private bool verboseDebugging = false;
// defaults
private string server = "localhost";
private string remotePath = ".";
private string username = "anonymous";
private string password = "anonymous@anonymous.net";
private string message = null;
private string result = null;
private int port = 21;
private int bytes = 0;
private int resultCode = 0;
private bool loggedin = false;
private bool binMode = false;
private Byte[] buffer = new Byte[BUFFER_SIZE];
private Socket clientSocket = null;
private int timeoutSeconds = 10;
/// <summary>
/// Default contructor
/// </summary>
public FtpClient()
{
}
/// <summary>
///
/// </summary>
/// <param name="server"></param>
/// <param name="username"></param>
/// <param name="password"></param>
public FtpClient(string server, string username, string password)
{
this.server = server;
this.username = username;
this.password = password;
}
/// <summary>
///
/// </summary>
/// <param name="server"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="timeoutSeconds"></param>
/// <param name="port"></param>
public FtpClient(string server, string username, string password, int timeoutSeconds, int port)
{
this.server = server;
this.username = username;
this.password = password;
this.timeoutSeconds = timeoutSeconds;
this.port = port;
}
/// <summary>
/// Display all communications to the debug log
/// </summary>
public bool VerboseDebugging
{
get
{
return this.verboseDebugging;
}
set
{
this.verboseDebugging = value;
}
}
/// <summary>
/// Remote server port. Typically TCP 21
/// </summary>
public int Port
{
get
{
return this.port;
}
set
{
this.port = value;
}
}
/// <summary>
/// Timeout waiting for a response from server, in seconds.
/// </summary>
public int Timeout
{
get
{
return this.timeoutSeconds;
}
set
{
this.timeoutSeconds = value;
}
}
/// <summary>
/// Gets and Sets the name of the FTP server.
/// </summary>
/// <returns></returns>
public string Server
{
get
{
return this.server;
}
set
{
this.server = value;
}
}
/// <summary>
/// Gets and Sets the port number.
/// </summary>
/// <returns></returns>
public int RemotePort
{
get
{
return this.port;
}
set
{
this.port = value;
}
}
/// <summary>
/// GetS and Sets the remote directory.
/// </summary>
public string RemotePath
{
get
{
return this.remotePath;
}
set
{
this.remotePath = value;
}
}
/// <summary>
/// Gets and Sets the username.
/// </summary>
public string Username
{
get
{
return this.username;
}
set
{
this.username = value;
}
}
/// <summary>
/// Gets and Set the password.
/// </summary>
public string Password
{
get
{
return this.password;
}
set
{
this.password = value;
}
}
/// <summary>
/// If the value of mode is true, set binary mode for downloads, else, Ascii mode.
/// </summary>
public bool BinaryMode
{
get
{
return this.binMode;
}
set
{
if ( this.binMode == value ) return;
if ( value )
sendCommand("TYPE I");
else
sendCommand("TYPE A");
if ( this.resultCode != 200 ) throw new FtpException(result.Substring(4));
}
}
/// <summary>
/// Login to the remote server.
/// </summary>
public void Login()
{
if ( this.loggedin ) this.Close();
Debug.WriteLine("Opening connection to " + this.server, "FtpClient" );
IPAddress addr = null;
IPEndPoint ep = null;
try
{
this.clientSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
addr = Dns.Resolve(this.server).AddressList[0];
ep = new IPEndPoint( addr, this.port );
this.clientSocket.Connect(ep);
}
catch(Exception ex)
{
// doubtfull
if ( this.clientSocket != null && this.clientSocket.Connected ) this.clientSocket.Close();
throw new FtpException("Couldn't connect to remote server",ex);
}
this.readResponse();
if(this.resultCode != 220)
{
this.Close();
throw new FtpException(this.result.Substring(4));
}
this.sendCommand( "USER " + username );
if( !(this.resultCode == 331 || this.resultCode == 230) )
{
this.cleanup();
throw new FtpException(this.result.Substring(4));
}
if( this.resultCode != 230 )
{
this.sendCommand( "PASS " + password );
if( !(this.resultCode == 230 || this.resultCode == 202) )
{
this.cleanup();
throw new FtpException(this.result.Substring(4));
}
}
this.loggedin = true;
Debug.WriteLine( "Connected to " + this.server, "FtpClient" );
this.ChangeDir(this.remotePath);
}
/// <summary>
/// Close the FTP connection.
/// </summary>
public void Close()
{
Debug.WriteLine("Closing connection to " + this.server, "FtpClient" );
if( this.clientSocket != null )
{
this.sendCommand("QUIT");
}
this.cleanup();
}
/// <summary>
/// Return a string array containing the remote directory's file list.
/// </summary>
/// <returns></returns>
public string[] GetFileList()
{
return this.GetFileList("*.*");
}
/// <summary>
/// Return a string array containing the remote directory's file list.
/// </summary>
/// <param name="mask"></param>
/// <returns></returns>
public string[] GetFileList(string mask)
{
if ( !this.loggedin ) this.Login();
Socket cSocket = createDataSocket();
this.sendCommand("NLST " + mask);
if(!(this.resultCode == 150 || this.resultCode == 125)) throw new FtpException(this.result.Substring(4));
this.message = "";
DateTime timeout = DateTime.Now.AddSeconds(this.timeoutSeconds);
while( timeout > DateTime.Now )
{
int bytes = cSocket.Receive(buffer, buffer.Length, 0);
this.message += ASCII.GetString(buffer, 0, bytes);
if ( bytes < this.buffer.Length ) break;
}
string[] msg = this.message.Replace("\r","").Split('\n');
cSocket.Close();
if ( this.message.IndexOf( "No such file or directory" ) != -1 )
msg = new string[]{};
this.readResponse();
if ( this.resultCode != 226 )
msg = new string[]{};
// throw new FtpException(result.Substring(4));
return msg;
}
/// <summary>
/// Return the size of a file.
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public long GetFileSize(string fileName)
{
if ( !this.loggedin ) this.Login();
this.sendCommand("SIZE " + fileName);
long size=0;
if ( this.resultCode == 213 )
size = long.Parse(this.result.Substring(4));
else
throw new FtpException(this.result.Substring(4));
return size;
}
/// <summary>
/// Download a file to the Assembly's local directory,
/// keeping the same file name.
/// </summary>
/// <param name="remFileName"></param>
public void Download(string remFileName)
{
this.Download(remFileName,"",false);
}
/// <summary>
/// Download a remote file to the Assembly's local directory,
/// keeping the same file name, and set the resume flag.
/// </summary>
/// <param name="remFileName"></param>
/// <param name="resume"></param>
public void Download(string remFileName,Boolean resume)
{
this.Download(remFileName,"",resume);
}
/// <summary>
/// Download a remote file to a local file name which can include
/// a path. The local file name will be created or overwritten,
/// but the path must exist.
/// </summary>
/// <param name="remFileName"></param>
/// <param name="locFileName"></param>
public void Download(string remFileName,string locFileName)
{
this.Download(remFileName,locFileName,false);
}
/// <summary>
/// Download a remote file to a local file name which can include
/// a path, and set the resume flag. The local file name will be
/// created or overwritten, but the path must exist.
/// </summary>
/// <param name="remFileName"></param>
/// <param name="locFileName"></param>
/// <param name="resume"></param>
public void Download(string remFileName,string locFileName,Boolean resume)
{
if ( !this.loggedin ) this.Login();
this.BinaryMode = true;
Debug.WriteLine("Downloading file " + remFileName + " from " + server + "/" + remotePath, "FtpClient" );
if (locFileName.Equals(""))
{
locFileName = remFileName;
}
FileStream output = null;
if ( !File.Exists(locFileName) )
output = File.Create(locFileName);
else
output = new FileStream(locFileName,FileMode.Open);
Socket cSocket = createDataSocket();
long offset = 0;
if ( resume )
{
offset = output.Length;
if ( offset > 0 )
{
this.sendCommand( "REST " + offset );
if ( this.resultCode != 350 )
{
//Server dosnt support resuming
offset = 0;
Debug.WriteLine("Resuming not supported:" + result.Substring(4), "FtpClient" );
}
else
{
Debug.WriteLine("Resuming at offset " + offset, "FtpClient" );
output.Seek( offset, SeekOrigin.Begin );
}
}
}
this.sendCommand("RETR " + remFileName);
if ( this.resultCode != 150 && this.resultCode != 125 )
{
throw new FtpException(this.result.Substring(4));
}
DateTime timeout = DateTime.Now.AddSeconds(this.timeoutSeconds);
while ( timeout > DateTime.Now )
{
this.bytes = cSocket.Receive(buffer, buffer.Length, 0);
output.Write(this.buffer,0,this.bytes);
if ( this.bytes <= 0)
{
break;
}
}
output.Close();
if ( cSocket.Connected ) cSocket.Close();
this.readResponse();
if( this.resultCode != 226 && this.resultCode != 250 )
throw new FtpException(this.result.Substring(4));
}
/// <summary>
/// Upload a file.
/// </summary>
/// <param name="fileName"></param>
public void Upload(string fileName)
{
this.Upload(fileName,false);
}
/// <summary>
/// Upload a file and set the resume flag.
/// </summary>
/// <param name="fileName"></param>
/// <param name="resume"></param>
public void Upload(string fileName, bool resume)
{
if ( !this.loggedin ) this.Login();
Socket cSocket = null ;
long offset = 0;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -