程式連接ftp 怎么寫,有哪位有愛心的大神級高手,提供一下思路或現成的代碼
uj5u.com熱心網友回復:
一個用C#寫的代碼,你看是否能用using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.FtpClient;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace FTP_Client
{
public class FTPConnection
{
public FTPConnection() { }
/// <summary>
/// 連接FTP服務器函式
/// </summary>
/// <param name="strServer">服務器IP</param>
/// <param name="strUser">用戶名</param>
/// <param name="strPassword">密碼</param>
public bool FTPIsConnected(string strServer, string strUser, string strPassword)
{
using (FtpClient ftp = new FtpClient())
{
ftp.Host = strServer;
ftp.Credentials = new NetworkCredential(strUser, strPassword);
ftp.Connect();
return ftp.IsConnected;
}
}
/// <summary>
/// FTP下載檔案
/// </summary>
/// <param name="strServer">服務器IP</param>
/// <param name="strUser">用戶名</param>
/// <param name="strPassword">密碼</param>
/// <param name="Serverpath">服務器路徑,例子:"/Serverpath/"</param>
/// <param name="localpath">本地保存路徑</param>
/// <param name="filetype">所下載的檔案型別,例子:".rte"</param>
public bool FTPIsdownload(string strServer, string strUser, string strPassword,string Serverpath, string localpath, string filetype)
{
FtpClient ftp = new FtpClient();
ftp.Host = strServer;
ftp.Credentials = new NetworkCredential(strUser, strPassword);
ftp.Connect();
string path = Serverpath;
string destinationDirectory = localpath;
List<string> documentname = new List<string>();
bool DownloadStatus = false;
if (Directory.Exists(destinationDirectory))
{
#region 從FTP服務器下載檔案
foreach (var ftpListItem in ftp.GetListing(path, FtpListOption.Modify | FtpListOption.Size)
.Where(ftpListItem => string.Equals(Path.GetExtension(ftpListItem.Name), filetype)))
{
string destinationPath = string.Format(@"{0}\{1}", destinationDirectory, ftpListItem.Name);
using (Stream ftpStream = ftp.OpenRead(ftpListItem.FullName))
using (FileStream fileStream = File.Create(destinationPath, (int)ftpStream.Length))
{
var buffer = new byte[200 * 1024];
int count;
while ((count = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, count);
}
}
documentname.Add(ftpListItem.Name);
}
#endregion
#region 驗證本地是否有該檔案
string[] files = Directory.GetFiles(localpath, "*"+filetype);
int filenumber = 0;
foreach(string strfilename in files)
{
foreach(string strrecievefile in documentname)
{
if (strrecievefile == Path.GetFileName(strfilename))
{
filenumber++;
break;
}
}
}
if(filenumber==documentname.Count)
{
DownloadStatus = true;
}
#endregion
}
return DownloadStatus;
}
}
}
uj5u.com熱心網友回復:
謝謝了,大神的幫助轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/41019.html
標籤:服務器
下一篇:RIP實驗
