FtpWebRequest reqFTP;
public void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string localFile = ftpFilePath + "/" + DateTime.Now.Year;
if(!Check(localFile))
{
FtpMakeDir(localFile);
}
localFile = localFile + "/" + DateTime.Now.Month;
if(!Check(localFile))
{
FtpMakeDir(localFile);
}
localFile = localFile + "/" + DateTime.Now.Day;
if(!Check(localFile))
{
FtpMakeDir(localFile);
}
string uri = "ftp://" + ftpServerIP + "/" + localFile + "/" + fileInf.Name;
Connect(uri);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
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)
{
CommonHelper.PrintLog("FTP传输文件出错!");
}
}
public Boolean Check(string localFile)
{
bool flag = true;
try
{
reqFTP = (FtpWebRequest) WebRequest.Create("ftp://" + ftpServerIP + "/" + localFile);
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse) reqFTP.GetResponse();
response.Close();
}
catch(Exception)
{
reqFTP.Abort();
flag = false;
}
return flag;
}
public Boolean FtpMakeDir(string localFile)
{
reqFTP = (FtpWebRequest) WebRequest.Create("ftp://" + ftpServerIP + "/" + localFile);
CommonHelper.PrintLog("创建路径" + "ftp://" + ftpServerIP + "/" + localFile);
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
try
{
reqFTP.UsePassive = true;
reqFTP.UseBinary = false;
reqFTP.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse) reqFTP.GetResponse();
response.Close();
}
catch(Exception ex)
{
CommonHelper.PrintLog("创建文件报错" + ex.ToString());
reqFTP.Abort();
return false;
}
reqFTP.Abort();
return true;
}
public void Connect(string path)
{
reqFTP = (FtpWebRequest) FtpWebRequest.Create(new Uri(path));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
}