TreeView1是.Net TreeView控件。請在WinForm界面上添加一個控件
Form1_load中的Dec是實例化ftpClient.vb的一個對象,ftpDetails是用來存儲FTP登錄憑據的。
Form1.vb
1Public Class Form1Class Form1
2
3 Dim ftp As ftpClient
4 Dim LocalFileList As New DataTable
5
6 Private Sub Form1_Load()Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
7 Dim Dec As New ftpClient.FtpDetails("www.cnblogs.com", 21, "cnblogVIP", "**********")
8 ftp = New ftpClient(Dec)
9 loadFtpTree(TreeView1.Nodes, "") '調用此代碼可以裝載遠程FTP結構樹
10
11 End Sub
12
13 '這個方法用於獲得遠程目錄及文件樹
14 Private Sub loadFtpTree()Sub loadFtpTree(ByVal Nodes As TreeNodeCollection, ByVal Path As String)
15 ''獲得各級分類
16 Dim sNode As Integer = -1
17 ''通過FTP獲得當前目錄列表
18 Dim result As String = ftp.GetFileList(Path)
19 Dim files() As String = Split(result, vbCrLf) '把FTP服務器返回的文本,分離出是目錄還是文件,文件或目錄名,文件大小
20 Dim ffi As New ftpClient.FtpListFileInfo
21 If files.Length > 0 Then
22 '加載節點
23 Dim I As Integer
24 For I = 0 To files.Length - 2
25 ffi.ParserString(files(I)) '對返回的單行做分割。分離出是目錄還是文件,文件或目錄名,文件大小
26 If ffi.IsDirectory = True And ffi.FileName <> ".." And ffi.FileName <> "." Then '如果是有效的目錄。
27 sNode += 1
28 Nodes.Add(0, ffi.FileName) '由於是目錄,前面的參數保存了類似.Tag一樣的作用,這裡保存了文件的size
29 Dim newpath As String = Path + "/" + ffi.FileName 'FileName如果是文件表示文件名,否則表示目錄名
30 Application.DoEvents()
31 '讀取當前節點的子節點加載()
32 loadFtpTree(Nodes(sNode).Nodes, newpath) '遞歸檢查當前目錄下是否有子目錄
33 ElseIf ffi.IsDirectory = False Then '如果是文件
34 sNode += 1
35 Nodes.Add(ffi.FileSize.ToString, ffi.FileName) '加入到節點中
36 End If
37 Next
38 End If
39 TreeView1.ExpandAll()
40 End Sub
ftpClient.vb
1 Imports System.Net
2 Imports System.IO
3
4Public Class ftpClientClass ftpClient
5
6 Public Ftp As FtpDetails = Nothing
7
8 Private ftpNetworkCredential As New NetworkCredential
9
10 Public Event ErrorMessage(ByVal Err As FtpError)
11
12 Public Class FtpErrorClass FtpError
13 Public ErrUrl As String = ""
14 Public ErrMsg As String = ""
15 Public Err As ErrType = ErrType.文件上傳
16
17 Public Enum ErrTypeEnum ErrType
18 文件上傳
19 目錄遍歷
20 目錄創建
21 列表清單
22 End Enum
23 End Class
24
25 Public Sub New()Sub New(ByVal _FTPDetails As FtpDetails)
26 ftpNetworkCredential.UserName = _FTPDetails.UserName
27 ftpNetworkCredential.Password = _FTPDetails.PassWord
28 Ftp = _FTPDetails
29 End Sub
30
31 Public Class FtpDetailsClass FtpDetails
32 Private _Host As String = ""
33 Private _Port As Integer = 0
34 Private _UserName As String = ""
35 Private _PassWord As String = ""
36
37 Public Sub New()Sub New(ByVal ftpHost As String, ByVal ftpPort As Integer, ByVal ftpUserName As String, ByVal ftpPassword As String)
38 If ftpHost = "" Then
39 Throw New Exception("請提供FTP服務器名稱或地址!")
40 End If
41 If ftpPort <= 0 Or ftpPort > 65535 Then
42 Throw New Exception("提供的端口不合法!")
43 End If
44 If ftpUserName = "" Then
45 ftpUserName = "anonymous"
46 End If
47 If ftpPassword = "" Then
48 ftpPassword = "[email protected]"
49 End If
50 _Host = ftpHost
51 _Port = ftpPort
52 _UserName = ftpUserName
53 _PassWord = ftpPassword
54 End Sub
55
56 /**/''' <summary>
57 ''' 獲得或設置FTP服務器IP地址(或域名)
58 ''' </summary>
59 ''' <value></value>
60 ''' <returns></returns>
61 ''' <remarks></remarks>
62 Property Host()Property Host() As String
63 Get
64 Return _Host
65 End Get
66 Set(ByVal value As String)
67 _Host = value
68 End Set
69 End Property
70
71 /**/''' <summary>
72 ''' 獲得或設置FTP服務器端口
73 ''' </summary>
74 ''' <value></value>
75 ''' <returns></returns>
76 ''' <remarks></remarks>
77 Property Port()Property Port() As Integer
78 Get
79 Return _Port
80 End Get
81 Set(ByVal value As Integer)
82 _Port = value
83 End Set
84 End Property
85
86 /**/''' <summary>
87 ''' 獲得或設置FTP登錄密碼
88 ''' </summary>
89 ''' <value></value>
90 ''' <returns></returns>
91 ''' <remarks></remarks>
92 Property UserName()Property UserName() As String
93 Get
94 Return _UserName
95 End Get
96 Set(ByVal value As String)
97 _UserName = value
98 End Set
99 End Property
100
101 /**/''' <summary>
102 ''' 獲得或設置FTP密碼
103 ''' </summary>
104 ''' <value></value>
105 ''' <returns></returns>
106 ''' <remarks></remarks>
107 Property PassWord()Property PassWord() As String
108 Get
109 Return _PassWord
110 End Get
111 Set(ByVal value As String)
112 _PassWord = value
113 End Set
114 End Property
115 End Class
116
117 Public Function GetFileList()Function GetFileList(ByVal strPath As String) As String
118 Try
119 Dim ftpUri As String = "ftp://" + Ftp.Host + ":" + Ftp.Port.ToString
120 If strPath <> "" Then
121 ftpUri += "/" + strPath
122 End If
123 Dim uri As New Uri(ftpUri)
124
125 Dim listRequest As FtpWebRequest '= DirectCast(WebRequest.Create(uri), FtpWebRequest)
126 listRequest = FtpWebRequest.Create(uri)
127 listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails
128
129 listRequest.Credentials = ftpNetworkCredential
130 listRequest.UsePassive = True
131 Dim listResponse As FtpWebResponse = DirectCast(listRequest.GetResponse(), FtpWebResponse)
132 Dim responseStream As Stream = listResponse.GetResponseStream()
133 Dim readStream As New StreamReader(responseStream, System.Text.Encoding.[Default])
134
135 Dim Result As String = ""
136 If readStream IsNot Nothing Then
137 Result = readStream.ReadToEnd()
138 End If
139
140 'MessageBox.Show(String.Format("狀態: {0},{1}", listResponse.StatusCode, listResponse.StatusDescription))
141
142 listResponse.Close()
143 responseStream.Close()
144 readStream.Close()
145 Return Result
146 Catch ex As Exception
147 Dim Err As New FtpError
148 Err.ErrMsg = ex.Message
149 Err.ErrUrl = strPath
150 Err.Err = FtpError.ErrType.列表清單
151 RaiseEvent ErrorMessage(Err)
152 Return ""
153 End Try
154 End Function
155
156 /**/''' <summary>
157 ''' STR Path是由/開頭的一個基於根目錄的地址
158 ''' </summary>
159 ''' <param name="strPath"></param>
160 ''' <returns></returns>
161 ''' <remarks></remarks>
162 Public Function CreateDirectory()Function CreateDirectory(ByVal strPath As String) As Boolean
163 Try
164 Dim ftpUri As String = "ftp://" + Ftp.Host + ":" + Ftp.Port.ToString
165 If strPath <> "" Then
166 ftpUri += "/" + strPath
167 End If
168 Dim uri As New Uri(ftpUri)
169
170 Dim listRequest As FtpWebRequest
171 listRequest = FtpWebRequest.Create(uri)
172 listRequest.Method = WebRequestMethods.Ftp.MakeDirectory
173
174 listRequest.Credentials = ftpNetworkCredential
175 listRequest.UsePassive = True
176 Dim listResponse As FtpWebResponse = DirectCast(listRequest.GetResponse(), FtpWebResponse)
177 'MessageBox.Show(String.Format("狀態: {0},{1}", listResponse.StatusCode, listResponse.StatusDescription))
178 listResponse.Close()
179 Return True
180 Catch ex As Exception
181 Dim Err As New FtpError
182 Err.ErrMsg = ex.Message
183 Err.ErrUrl = strPath
184 Err.Err = FtpError.ErrType.目錄創建
185 RaiseEvent ErrorMessage(Err)
186 Return False
187 End Try
188 End Function
189
190 Public Function uploadFile()Function uploadFile(ByVal strPath As String, ByVal strFullName As String) As Boolean
191 Dim ftpUri As String = "ftp://" + Ftp.Host + ":" + Ftp.Port.ToString
192 If strPath <> "" Then
193 ftpUri += "/" + strPath
194 End If
195 Dim reqFTP As FtpWebRequest
196 reqFTP = FtpWebRequest.Create(ftpUri)
197 reqFTP.Credentials = ftpNetworkCredential
198 reqFTP.KeepAlive = True
199 reqFTP.Method = WebRequestMethods.Ftp.UploadFile
200 reqFTP.UseBinary = True
201 Dim f As New FileInfo(strFullName)
202
203 reqFTP.ContentLength = f.Length
204
205 Dim buffLength As Integer = 2048
206 Dim buff(buffLength) As Byte
207 Dim contentLen As Long
208 Dim Fs As FileStream = f.OpenRead
209 Try
210 Dim strm As Stream = reqFTP.GetRequestStream()
211 '每次讀文件流的2KB
212 contentLen = Fs.Read(buff, 0, buffLength)
213 Dim StartBye As Long = 0
214 While contentLen <> 0
215 strm.Write(buff, 0, contentLen)
216 contentLen = Fs.Read(buff, 0, buffLength)
217 StartBye += contentLen
218 End While
219 Fs.Close()
220 strm.Close()
221 Return True
222 Catch ex As Exception
223 Dim Err As New FtpError
224 Err.ErrMsg = ex.Message + " 本地文件:" + strFullName
225 Err.ErrUrl = strPath
226 Err.Err = FtpError.ErrType.文件上傳
227 RaiseEvent ErrorMessage(Err)
228 Return False
229 End Try
230 End Function
231
232
233 Public Class FtpListFileInfoClass FtpListFileInfo
234 Public IsDirectory As Boolean = False
235 Public FileSize As Long = 0
236 Public FileName As String = ""
237
238 Public Sub ParserString()Sub ParserString(ByVal str As String)
239 If str = "" Then Exit Sub
240 Try
241 If Strings.Left(str, 1) = "d" Then
242 IsDirectory = True
243 Else
244 IsDirectory = False
245 End If
246 '取得文件長度
247 FileSize = CLng(Trim(Strings.Mid(str, 31, 12)))
248 FileName = Trim(Strings.Right(str, str.Length - 55))
249 Catch ex As Exception
250 IsDirectory = False
251 FileSize = 0
252 FileName = ""
253 End Try
254 End Sub
255 End Class
256End Class
257