c#上傳Ftp文件,創建文件夾


 

  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);//連接
// 默認為true,連接不會被關閉
// 在一個命令之后被執行
reqFTP.KeepAlive = false;
// 指定執行什么命令
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// 上傳文件時通知服務器文件的大小
reqFTP.ContentLength = fileInf.Length;
// 緩沖大小設置為kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];

int contentLen;
// 打開一個文件流(System.IO.FileStream) 去讀上傳的文件
FileStream fs = fileInf.OpenRead();

try
{
// 把上傳的文件寫入流
Stream strm = reqFTP.GetRequestStream();
// 每次讀文件流的kb
contentLen = fs.Read(buff, 0, buffLength);
// 流內容沒有結束
while (contentLen != 0)
{
// 把內容從file stream 寫入upload stream
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;
}

/// <summary>
/// FTP連接
/// </summary>
/// <param name="path"></param>

public void Connect(string path)
{
// 根據uri創建FtpWebRequest對象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
// 指定數據傳輸類型
reqFTP.UseBinary = true;
// ftp用戶名和密碼
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM