#region 上传和下载
/// <summary>
/// 下载一批文件
/// </summary>
/// <param name="strFileNameMask">文件名的匹配字符串</param>
/// <param name="strFolder">本地目录(不得以\结束)</param>
public void Get(string strFileNameMask,string strFolder)
{
if(!bConnected)
{
Connect();
}
string[] strFiles = Dir(strFileNameMask);
foreach(string strFile in strFiles)
{
if(!strFile.Equals(""))//一般来说strFiles的最后一个元素可能是空字符串
{
Get(strFile,strFolder,strFile);
}
}
}
/// <summary>
/// 下载一个文件
/// </summary>
/// <param name="strRemoteFileName">要下载的文件名</param>
/// <param name="strFolder">本地目录(不得以\结束)</param>
/// <param name="strLocalFileName">保存在本地时的文件名</param>
public void Get(string strRemoteFileName,string strFolder,string strLocalFileName)
{
if(!bConnected)
{
Connect();
}
SetTransferType(TransferType.Binary);
if (strLocalFileName.Equals(""))
{
strLocalFileName = strRemoteFileName;
}
if(!File.Exists(strLocalFileName))
{
Stream st = File.Create(strLocalFileName);
st.Close();
}
FileStream output = new
FileStream(strFolder + "\\" + strLocalFileName,FileMode.Create);
Socket socketData = CreateDataSocket();
SendCommand("RETR " + strRemoteFileName);
if(!(iReplyCode == 150 || iReplyCode == 125
|| iReplyCode == 226 || iReplyCode == 250))
{
throw new IOException(strReply.Substring(4));
}
while(true)
{
int iBytes = socketData.Receive(buffer, buffer.Length, 0);
output.Write(buffer,0,iBytes);
if(iBytes <= 0)
{
break;
}
}
output.Close();
if (socketData.Connected)
{
socketData.Close();
}
if(!(iReplyCode == 226 || iReplyCode == 250))
{
ReadReply();
if(!(iReplyCode == 226 || iReplyCode == 250))
{
throw new IOException(strReply.Substring(4));
}
}
}
/// <summary>
/// 上传一批文件
/// </summary>
/// <param name="strFolder">本地目录(不得以\结束)</param>
/// <param name="strFileNameMask">文件名匹配字符(可以包含*和?)</param>
public void Put(string strFolder,string strFileNameMask)
{
string[] strFiles = Directory.GetFiles(strFolder,strFileNameMask);
foreach(string strFile in strFiles)
{
//strFile是完整的文件名(包含路径)
Put(strFile);
}
}
/// <summary>
/// 上传一个文件
/// </summary>
/// <param name="strFileName">本地文件名</param>
public void Put(string strFileName)
{
if(!bConnected)
{
Connect();
}
Socket socketData = CreateDataSocket();
SendCommand("STOR "+Path.GetFileName(strFileName));
if( !(iReplyCode == 125 || iReplyCode == 150) )
{
throw new IOException(strReply.Substring(4));
}
FileStream input = new
FileStream(strFileName,FileMode.Open);
int iBytes = 0;
while ((iBytes = input.Read(buffer,0,buffer.Length)) > 0)
{
socketData.Send(buffer, iBytes, 0);
}
input.Close();
if (socketData.Connected)
{
socketData.Close();
}
if(!(iReplyCode == 226 || iReplyCode == 250))
{
ReadReply();
if(!(iReplyCode == 226 || iReplyCode == 250))
{
throw new IOException(strReply.Substring(4));
}
}
}
#endregion
网络转载