利用FtpWebRequest列出FTP位置檔案結構
在FTP的操作中,有時會遇到需要列出FTP站台中,檔案、目錄相關的結構;而利用FtpWebRequest所提供的相關方法去取得時,取回的會像是下面這樣的一串文字
從結果可以看出,在資料夾的部分會出現DIR這樣樣的字樣,一般的檔案則是出現檔案名稱,但是這樣的方式要列出整個檔案結構是比較不直覺、方便的,不過我們可以利用這些資訊加工之後,就可以達到樹狀檢視這樣的效果。
試寫了一下,UI部分很簡單,只有一個按鈕以及treeview
程式碼的部分大概會像是下面這樣
從結果可以看出,在資料夾的部分會出現DIR這樣樣的字樣,一般的檔案則是出現檔案名稱,但是這樣的方式要列出整個檔案結構是比較不直覺、方便的,不過我們可以利用這些資訊加工之後,就可以達到樹狀檢視這樣的效果。
試寫了一下,UI部分很簡單,只有一個按鈕以及treeview
程式碼的部分大概會像是下面這樣
private void btnRefresh_Click(object sender, EventArgs e) { TreeNode root = new TreeNode("ftproot"); treeView1.Nodes.Add(root); ftppath = string.Empty; InserNodeData(ref root, string.Empty); root = null; } string ftppath = string.Empty; private void InserNodeData(ref TreeNode node,string secondPath) { List<clsFTPData> child = new List<clsFTPData>(); ListFtpFiles(ref child, ftppath); var childitems = from o in child orderby o.DataType, o.DataName select o; foreach (clsFTPData childitem in childitems) { TreeNode newChild = new TreeNode(); if (childitem.DataType == 0) { newChild.Text = childitem.DataName; newChild.ImageIndex = 0; ftppath += childitem.DataName + @"/"; InserNodeData(ref newChild, childitem.DataName); } else { newChild.Text = childitem.DataName; newChild.ImageIndex = 1; } node.Nodes.Add(newChild); newChild = null; } if (!string.IsNullOrEmpty(ftppath)) { ftppath = ftppath.Substring(0, ftppath.Length - 1); ftppath = ftppath.Substring(0, ftppath.LastIndexOf(@"/") + 1); } child = null; childitems = null; } private void ListFtpFiles(ref List<clsFTPData> result,string FtpPath) { // Get the object used to communicate with the server. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(@"ftp://192.168.2.177/" + FtpPath)); request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential("ftpuser", "ftpuser"); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); Encoding big5 = Encoding.GetEncoding("big5"); StreamReader reader = new StreamReader(responseStream, big5); string[] data; data = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (string item in data) { clsFTPData newitem = new clsFTPData(); if (item.IndexOf("") >= 0) { newitem.DataType = 0; newitem.DataName = item.Substring(item.IndexOf(" ") + 5).Trim(); } else { newitem.DataType = 1; newitem.DataName = item.Substring(18).Trim(); } result.Add(newitem); newitem = null; } reader.Close(); reader.Dispose(); response.Close(); response = null; request = null; }
留言
類別中只有兩個屬性,參考看看
class clsFTPData
{
public int DataType { get; set; }
public string DataName { get; set; }
}