当前位置: 编程技术>.net/c#/asp.net
C#版ftp方法实现类的代码
来源: 互联网 发布时间:2014-10-13
本文导语: /* FTPFactory.cs Better view with tab space=4 Written by Jaimon Mathew (jaimonmathew@rediffmail.com) Rolander,Dan (Dan.Rolander@marriott.com) has modified the download method to cope with file name with path information. He also provided the XML comments s...
/*
FTPFactory.cs
Better view with tab space=4
Written by Jaimon Mathew (jaimonmathew@rediffmail.com)
Rolander,Dan (Dan.Rolander@marriott.com) has modified the
download
method to cope with file name with path information. He also
provided
the XML comments so that the library provides Intellisense
descriptions.
use the following line to compile
csc /target:library /out:FTPLib.dll /r:System.DLL FTPFactory.cs
*/
using System;
using System.Threading;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Sockets;
using System.Configuration;
namespace AudioCollect
{
///
/// FTPFactory 的摘要说明。
///
public class FTPFactory
{
static readonly log4net.ILog log = log4net.LogManager.GetLogger("log4net");
private string
remoteHost,remotePath,remoteUser,remotePass,mes;
private int remotePort,bytes;
private Socket clientSocket;
private int retValue;
private Boolean debug;
private Boolean logined;
private string reply;
private static int BLOCK_SIZE = 512;
Byte[] buffer = new Byte[BLOCK_SIZE];
Encoding ASCII = Encoding.ASCII;
public FTPFactory()
{
string FTPRemoteIP = ConfigurationSettings.AppSettings["FTPRemoteIP"];
int FTPRemotePort = Convert.ToInt32( ConfigurationSettings.AppSettings["FTPRemotePort"] );
string FTPUser = ConfigurationSettings.AppSettings["FTPUser"];
string FTPPassword = ConfigurationSettings.AppSettings["FTPPassword"];
remoteHost = FTPRemoteIP;
remotePath = ".";
remoteUser = FTPUser;
remotePass = FTPPassword;
remotePort =FTPRemotePort;
debug = false;
logined = false;
}
///
/// Set the name of the FTP server to connect to.
///
/// Server name
public void setRemoteHost(string remoteHost)
{
this.remoteHost = remoteHost;
}
///
/// Return the name of the current FTP server.
///
/// Server name
public string getRemoteHost()
{
return remoteHost;
}
///
/// Set the port number to use for FTP.
///
/// Port number
public void setRemotePort(int remotePort)
{
this.remotePort = remotePort;
}
///
/// Return the current port number.
///
/// Current port number
public int getRemotePort()
{
return remotePort;
}
///
/// Set the remote directory path.
///
/// The remote directory path
public void setRemotePath(string remotePath)
{
this.remotePath = remotePath;
}
///
/// Return the current remote directory path.
///
/// The current remote directory path.
public string getRemotePath()
{
return remotePath;
}
///
/// Set the user name to use for logging into the remote server.
///
/// Username
public void setRemoteUser(string remoteUser)
{
this.remoteUser = remoteUser;
}
///
/// Set the password to user for logging into the remote server.
///
/// Password
public void setRemotePass(string remotePass)
{
this.remotePass = remotePass;
}
///
/// Return a string array containing the remote directory's file list.
///
///
///
public string[] getFileList(string mask)
{
if(!logined)
{
login();
}
Socket cSocket = createDataSocket();
sendCommand("NLST " + mask);
if(!(retValue == 150 || retValue == 125))
{
throw new IOException(reply.Substring(4));
}
mes = "";
Thread.Sleep(700);
while(true)
{
if(cSocket.Connected)
{
int bytes = cSocket.Receive(buffer, buffer.Length, 0);
mes += ASCII.GetString(buffer, 0, bytes);
if(bytes 0 )
{
setBinaryMode(false);
sendCommand("REST "+offset);
if(retValue != 350)
{
//throw new IOException(reply.Substring(4));
//Some servers may not support resuming.
offset = 0;
}
}
if(offset > 0)
{
if(debug)
{
Console.WriteLine("seeking to " + offset);
}
long npos = output.Seek(offset,SeekOrigin.Begin);
Console.WriteLine("new pos="+npos);
}
}
sendCommand("RETR " + remFileName);
if(!(retValue == 150 || retValue == 125))
{
throw new IOException(reply.Substring(4));
}
while(true)
{
bytes = cSocket.Receive(buffer, buffer.Length, 0);
output.Write(buffer,0,bytes);
if(bytes 0 )
{
sendCommand("REST " + offset);
if(retValue != 350)
{
//throw new IOException(reply.Substring(4));
//Remote server may not support resuming.
offset = 0;
}
}
/*==========================*/
sendCommand("STOR "+Path.GetFileName(fileName));
if( !(retValue == 125 || retValue == 150) )
{
throw new IOException(reply.Substring(4));
}
// open input stream to read source file
FileStream input = new FileStream(fileName,FileMode.Open);
if(offset != 0)
{
if(debug)
{
Console.WriteLine("seeking to " + offset);
}
input.Seek(offset,SeekOrigin.Begin);
}
Console.WriteLine("Uploading file "+fileName+" to "+remotePath);
while ((bytes = input.Read(buffer,0,buffer.Length)) > 0)
{
cSocket.Send(buffer, bytes, 0);
}
input.Close();
Console.WriteLine("");
if (cSocket.Connected)
{
cSocket.Close();
}
readReply();
if( !(retValue == 226 || retValue == 250) )
{
throw new IOException(reply.Substring(4));
}
}
///
/// Delete a file from the remote FTP server.
///
///
public void deleteRemoteFile(string fileName)
{
if(!logined)
{
login();
}
sendCommand("DELE "+fileName);
if(retValue != 250)
{
throw new IOException(reply.Substring(4));
}
}
///
/// Rename a file on the remote FTP server.
///
///
///
public void renameRemoteFile(string oldFileName,string
newFileName)
{
if(!logined)
{
login();
}
sendCommand("RNFR "+oldFileName);
if(retValue != 350)
{
throw new IOException(reply.Substring(4));
}
// known problem
// rnto will not take care of existing file.
// i.e. It will overwrite if newFileName exist
sendCommand("RNTO "+newFileName);
if(retValue != 250)
{
throw new IOException(reply.Substring(4));
}
}
///
/// Create a directory on the remote FTP server.
///
///
public void mkdir(string dirName)
{
if(!logined)
{
login();
}
sendCommand("MKD "+dirName);
if(retValue != 250)
{
throw new IOException(reply.Substring(4));
}
}
///
/// Delete a directory on the remote FTP server.
///
///
public void rmdir(string dirName)
{
if(!logined)
{
login();
}
sendCommand("RMD "+dirName);
if(retValue != 250)
{
throw new IOException(reply.Substring(4));
}
}
///
/// Change the current working directory on the remote FTP server.
///
///
public void chdir(string dirName)
{
if(dirName.Equals("."))
{
return;
}
if(!logined)
{
login();
}
sendCommand("CWD "+dirName);
if(retValue != 250)
{
throw new IOException(reply.Substring(4));
}
this.remotePath = dirName;
Console.WriteLine("Current directory is "+remotePath);
}
///
/// Close the FTP connection.
///
public void close()
{
if( clientSocket != null )
{
sendCommand("QUIT");
}
cleanup();
Console.WriteLine("Closing...");
}
///
/// Set debug mode.
///
///
public void setDebug(Boolean debug)
{
this.debug = debug;
}
private void readReply()
{
mes = "";
reply = readLine();
retValue = Int32.Parse(reply.Substring(0,3));
}
private void cleanup()
{
if(clientSocket!=null)
{
clientSocket.Close();
clientSocket = null;
}
logined = false;
}
private string readLine()
{
while(true)
{
bytes = clientSocket.Receive(buffer, buffer.Length, 0);
mes += ASCII.GetString(buffer, 0, bytes);
if(bytes 2)
{
mes = mess[mess.Length-2];
}
else
{
mes = mess[0];
}
if(!mes.Substring(3,1).Equals(" "))
{
return readLine();
}
if(debug)
{
for(int k=0;k
FTPFactory.cs
Better view with tab space=4
Written by Jaimon Mathew (jaimonmathew@rediffmail.com)
Rolander,Dan (Dan.Rolander@marriott.com) has modified the
download
method to cope with file name with path information. He also
provided
the XML comments so that the library provides Intellisense
descriptions.
use the following line to compile
csc /target:library /out:FTPLib.dll /r:System.DLL FTPFactory.cs
*/
using System;
using System.Threading;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Sockets;
using System.Configuration;
namespace AudioCollect
{
///
/// FTPFactory 的摘要说明。
///
public class FTPFactory
{
static readonly log4net.ILog log = log4net.LogManager.GetLogger("log4net");
private string
remoteHost,remotePath,remoteUser,remotePass,mes;
private int remotePort,bytes;
private Socket clientSocket;
private int retValue;
private Boolean debug;
private Boolean logined;
private string reply;
private static int BLOCK_SIZE = 512;
Byte[] buffer = new Byte[BLOCK_SIZE];
Encoding ASCII = Encoding.ASCII;
public FTPFactory()
{
string FTPRemoteIP = ConfigurationSettings.AppSettings["FTPRemoteIP"];
int FTPRemotePort = Convert.ToInt32( ConfigurationSettings.AppSettings["FTPRemotePort"] );
string FTPUser = ConfigurationSettings.AppSettings["FTPUser"];
string FTPPassword = ConfigurationSettings.AppSettings["FTPPassword"];
remoteHost = FTPRemoteIP;
remotePath = ".";
remoteUser = FTPUser;
remotePass = FTPPassword;
remotePort =FTPRemotePort;
debug = false;
logined = false;
}
///
/// Set the name of the FTP server to connect to.
///
/// Server name
public void setRemoteHost(string remoteHost)
{
this.remoteHost = remoteHost;
}
///
/// Return the name of the current FTP server.
///
/// Server name
public string getRemoteHost()
{
return remoteHost;
}
///
/// Set the port number to use for FTP.
///
/// Port number
public void setRemotePort(int remotePort)
{
this.remotePort = remotePort;
}
///
/// Return the current port number.
///
/// Current port number
public int getRemotePort()
{
return remotePort;
}
///
/// Set the remote directory path.
///
/// The remote directory path
public void setRemotePath(string remotePath)
{
this.remotePath = remotePath;
}
///
/// Return the current remote directory path.
///
/// The current remote directory path.
public string getRemotePath()
{
return remotePath;
}
///
/// Set the user name to use for logging into the remote server.
///
/// Username
public void setRemoteUser(string remoteUser)
{
this.remoteUser = remoteUser;
}
///
/// Set the password to user for logging into the remote server.
///
/// Password
public void setRemotePass(string remotePass)
{
this.remotePass = remotePass;
}
///
/// Return a string array containing the remote directory's file list.
///
///
///
public string[] getFileList(string mask)
{
if(!logined)
{
login();
}
Socket cSocket = createDataSocket();
sendCommand("NLST " + mask);
if(!(retValue == 150 || retValue == 125))
{
throw new IOException(reply.Substring(4));
}
mes = "";
Thread.Sleep(700);
while(true)
{
if(cSocket.Connected)
{
int bytes = cSocket.Receive(buffer, buffer.Length, 0);
mes += ASCII.GetString(buffer, 0, bytes);
if(bytes 0 )
{
setBinaryMode(false);
sendCommand("REST "+offset);
if(retValue != 350)
{
//throw new IOException(reply.Substring(4));
//Some servers may not support resuming.
offset = 0;
}
}
if(offset > 0)
{
if(debug)
{
Console.WriteLine("seeking to " + offset);
}
long npos = output.Seek(offset,SeekOrigin.Begin);
Console.WriteLine("new pos="+npos);
}
}
sendCommand("RETR " + remFileName);
if(!(retValue == 150 || retValue == 125))
{
throw new IOException(reply.Substring(4));
}
while(true)
{
bytes = cSocket.Receive(buffer, buffer.Length, 0);
output.Write(buffer,0,bytes);
if(bytes 0 )
{
sendCommand("REST " + offset);
if(retValue != 350)
{
//throw new IOException(reply.Substring(4));
//Remote server may not support resuming.
offset = 0;
}
}
/*==========================*/
sendCommand("STOR "+Path.GetFileName(fileName));
if( !(retValue == 125 || retValue == 150) )
{
throw new IOException(reply.Substring(4));
}
// open input stream to read source file
FileStream input = new FileStream(fileName,FileMode.Open);
if(offset != 0)
{
if(debug)
{
Console.WriteLine("seeking to " + offset);
}
input.Seek(offset,SeekOrigin.Begin);
}
Console.WriteLine("Uploading file "+fileName+" to "+remotePath);
while ((bytes = input.Read(buffer,0,buffer.Length)) > 0)
{
cSocket.Send(buffer, bytes, 0);
}
input.Close();
Console.WriteLine("");
if (cSocket.Connected)
{
cSocket.Close();
}
readReply();
if( !(retValue == 226 || retValue == 250) )
{
throw new IOException(reply.Substring(4));
}
}
///
/// Delete a file from the remote FTP server.
///
///
public void deleteRemoteFile(string fileName)
{
if(!logined)
{
login();
}
sendCommand("DELE "+fileName);
if(retValue != 250)
{
throw new IOException(reply.Substring(4));
}
}
///
/// Rename a file on the remote FTP server.
///
///
///
public void renameRemoteFile(string oldFileName,string
newFileName)
{
if(!logined)
{
login();
}
sendCommand("RNFR "+oldFileName);
if(retValue != 350)
{
throw new IOException(reply.Substring(4));
}
// known problem
// rnto will not take care of existing file.
// i.e. It will overwrite if newFileName exist
sendCommand("RNTO "+newFileName);
if(retValue != 250)
{
throw new IOException(reply.Substring(4));
}
}
///
/// Create a directory on the remote FTP server.
///
///
public void mkdir(string dirName)
{
if(!logined)
{
login();
}
sendCommand("MKD "+dirName);
if(retValue != 250)
{
throw new IOException(reply.Substring(4));
}
}
///
/// Delete a directory on the remote FTP server.
///
///
public void rmdir(string dirName)
{
if(!logined)
{
login();
}
sendCommand("RMD "+dirName);
if(retValue != 250)
{
throw new IOException(reply.Substring(4));
}
}
///
/// Change the current working directory on the remote FTP server.
///
///
public void chdir(string dirName)
{
if(dirName.Equals("."))
{
return;
}
if(!logined)
{
login();
}
sendCommand("CWD "+dirName);
if(retValue != 250)
{
throw new IOException(reply.Substring(4));
}
this.remotePath = dirName;
Console.WriteLine("Current directory is "+remotePath);
}
///
/// Close the FTP connection.
///
public void close()
{
if( clientSocket != null )
{
sendCommand("QUIT");
}
cleanup();
Console.WriteLine("Closing...");
}
///
/// Set debug mode.
///
///
public void setDebug(Boolean debug)
{
this.debug = debug;
}
private void readReply()
{
mes = "";
reply = readLine();
retValue = Int32.Parse(reply.Substring(0,3));
}
private void cleanup()
{
if(clientSocket!=null)
{
clientSocket.Close();
clientSocket = null;
}
logined = false;
}
private string readLine()
{
while(true)
{
bytes = clientSocket.Receive(buffer, buffer.Length, 0);
mes += ASCII.GetString(buffer, 0, bytes);
if(bytes 2)
{
mes = mess[mess.Length-2];
}
else
{
mes = mess[0];
}
if(!mes.Substring(3,1).Equals(" "))
{
return readLine();
}
if(debug)
{
for(int k=0;k