HT_FTP程序
SVN 代碼地址
程序邏輯:
- 從數(shù)據(jù)庫(kù)中查詢數(shù)據(jù) 生成CSV文件 上傳FTP服務(wù)器
程序涉及方法
- 生成CSV文件方法:
- System.IO.FileInfo fi=new System.IO.FileInfo 提供建立博投、複製休傍、刪除筒溃、移動(dòng)和開(kāi)啟檔案的執(zhí)行個(gè)體
- System.IO.FileStream fs = new System.IO.FileStream() 提供使用指定路徑、建立模式和讀取/寫(xiě)入使用權(quán)限,來(lái)初始化 System.IO.FileStream 類別的新執(zhí)行個(gè)體
- fi.Directory.Exists 取得值,指出目錄是否存在
- Create() 創(chuàng)建文件;
- StreamWriter()使用預(yù)設(shè)編碼方式和緩衝區(qū)大小
- WriteLine()晚岭;Write()寫(xiě)入方法
- FTP 方法:
public void Connect(String path)//連接ftp
{
// 根據(jù)uri創(chuàng)建FtpWebRequest對(duì)象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
// 指定數(shù)據(jù)傳輸類型
reqFTP.UseBinary = true;
// ftp用戶名和密碼
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
}
- Upload 方法
public void Upload(string filename) //上面的代碼實(shí)現(xiàn)了從ftp服務(wù)器上載文件的功能
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpServerIP + fileInf.Name;
Connect(uri);//連接
// 默認(rèn)為true,連接不會(huì)被關(guān)閉
// 在一個(gè)命令之后被執(zhí)行
reqFTP.KeepAlive = false;
// 指定執(zhí)行什么命令
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// 上傳文件時(shí)通知服務(wù)器文件的大小
reqFTP.ContentLength = fileInf.Length;
// 緩沖大小設(shè)置為kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// 打開(kāi)一個(gè)文件流(System.IO.FileStream) 去讀上傳的文件
FileStream fs = fileInf.OpenRead();
try
{
//使用 HTTP Proxy 時(shí)勋功,不支援要求的 FTP 命令坦报。
//要解決以上問(wèn)題,只需要在代碼中指定
reqFTP.Proxy = GlobalProxySelection.GetEmptyWebProxy();
//或
//reqFTP.Proxy = null;
// 把上傳的文件寫(xiě)入流
Stream strm = reqFTP.GetRequestStream();
// 每次讀文件流的kb
contentLen = fs.Read(buff, 0, buffLength);
// 流內(nèi)容沒(méi)有結(jié)束
while (contentLen != 0)
{
// 把內(nèi)容從file stream 寫(xiě)入upload stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// 關(guān)閉兩個(gè)流
strm.Close();
fs.Close();
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message, "Upload Error");
throw ex;
}
}
-Delete() 刪除指定的檔案 刪除本地保存文件