为了说明在你的.Net应用程序中使用FTP 的可用性, 我将建立访问FTP 服务器Windows应用程序相片查看器。使用这种应用程序, 用户能上传相片到FTP 服务器和同时查看存放在FTP 服务器的图片。这种应用对于一些需要存取由他的伙伴公司上传的图像的公司是非常有用的。一个很好例子是保险公司, 他们可能需要由车间机械工观看汽车损伤的相片去估计修理费。而不是建立一种复杂web应用, 车间和保险公司可能简单地使用这种应用上传相片和迅速观看相片。.
图一是程序完成时的界面
创建应用程序
使用 Visual Studio 2005, 新建一个名为PhotoViewer的Windows应用程序. 添加 Form1 并在上面放置以下控件如 图 2 所示:
- Button
- GroupBox
- Label
- PictureBox
- TextBox
- ToolStripStatusLabel
- TreeView
![]() 图 1.
完成的图片查看器应用程序
. | ![]() 图 2. form1中各种控件布局. |
除了上边所列控件外, 你还需要添加一个ImageList到Form1中,ImageList包含三个图像代表一个被打开的文件夹、一个闭合的文件夹, 和图像文件. 你能具体指定这些图片在控件中的属性(请看 图 3).
你还需要通过TreeView的ImageList属性将ImageList和TreeView关联 (TreeView1).
创建目录树和查看图片
切换到form1的后台代码,导入下面的名称空间:
Imports System.Net
Imports System.IO
Public Class Form1
'---FTP server---
Const ftpServer As String = "ftp://127.0.0.1"
'---图标图像常量---
Const icoOpen = 0
Const icoClose = 1
Const icoPhoto = 2
'---FTP server登录证书(用户名和密码)---
Private Username As String = "anonymous"
Private Password As String = "password"
当表单加载,显示根目录节点:
Private Sub Form1_Load( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Try
'—-create the root node for the TreeView—-
Dim node As New TreeNode
node.ImageIndex = icoClose
node.SelectedImageIndex = icoOpen
node.Text = "/"
'---add the root node to the control---
TreeView1.Nodes.Add(node)
'—-add the dummy child node to the root node—-
node.Nodes.Add("")
'---select the root node---
TreeView1.SelectedNode = node
Catch err As Exception
MsgBox(err.ToString)
End Try
End Sub
![]() | |
图 3. 添加三个图像文件到ImageList控件. |
并且,如果节点被选择您应该改变当前的图示到"open" 和如果节点不被选择改为"closed" 。下面的代码为展开的文件夹和和各个节点适当的图标(五邑技术网编译):
Private Sub TreeView1_BeforeExpand( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) _
Handles TreeView1.BeforeExpand
'---if leaf node (photo) then exit---
If e.Node.ImageIndex = icoPhoto Then Return
'---remove the dummy node and display
' the subdirectories and files---
Try
'---clears all the nodes and...---
e.Node.Nodes.Clear()
'---create the nodes again---
BuildDirectory(e.Node)
Catch err As Exception
ToolStripStatusLabel1.Text = err.ToString
End Try
'---change the icon for this node to open---
If e.Node.GetNodeCount(False) > 0 Then
e.Node.ImageIndex = icoClose
e.Node.SelectedImageIndex = icoOpen
End If
End Sub
'---Get the file/dir listings and return them as a string array---
Private Function GetDirectoryListing(ByVal path As String) _
As String()
Try
Dim ftpReq As FtpWebRequest = WebRequest.Create(path)
ftpReq.Method = WebRequestMethods.Ftp.ListDirectoryDetails
ftpReq.Credentials = New NetworkCredential( _
Username, Password)
Dim FTPResp As FtpWebResponse = ftpReq.GetResponse
Dim ftpRespStream As Stream = FTPResp.GetResponseStream
Dim reader As StreamReader
reader = New StreamReader( _
ftpRespStream, System.Text.Encoding.UTF8)
'---obtain the result as a string array---
Dim result() As String = reader.ReadToEnd.Split(vbLf)
FTPResp.Close()
Return result
Catch ex As Exception
MsgBox(ex.ToString)
Return Nothing
End Try
End Function
![]() | |
图 4. 在一个节点中放入一个虚拟节点,使之成为可展开. |
- 使用WebRequest类的Create()方法创建一个FtpWebRequest实例,Create() 方法采取URI参数(包含完整的FTP路径).
- 使用FtpWebRequest 的方法属性,设置命令发到FTP服务器,在这种情况下,这个命令是ListDirectoryDetails.
- 使用指定的认证登录到FTP服务器.
-
使用ftpwebrequest类中getresponse ()方法从FTP服务器获得回应 .
-
使用ftpwebresponse类中getresponsestream()方法,从FTP服务器的响应数据取出流数据.
-
你可以使用一个streamreader对象读取目录列表.
12-11-06 10:54PM 2074750 DSC00098.JPG
12-11-06 10:54PM 2109227 DSC00099.JPG
12-11-06 10:49PM <DIR> George
12-11-06 10:49PM <DIR> James
12-11-06 10:58PM <DIR> Wei-Meng Lee
作者注:这篇文章,我用Windows XP中ftp服务,. 还注意到,你需要给写权限的用户,使他们能够创造新的目录和上传 档案复制到FTP服务器. 此文件由五邑技术网翻译 |
因为所有子目录都有"<DIR>"字段,所以你可以很简单地能过从BuildDirectory()子程序的文件中查找"<DIR>"字符来区分子目录:
'---Build the directory in the TreeView control---
Private Sub BuildDirectory(ByVal ParentNode As TreeNode)
Dim listing() As String = _
GetDirectoryListing(ftpServer & ParentNode.FullPath)
For Each line As String In listing
If line = String.Empty Then Exit For
Dim node As New TreeNode
If line.Substring(24, 5) = "
" Then
'---this is a directory---
'---create a new node to be added---
With node
.Text = line.Substring(39)
.ImageIndex = icoClose
.SelectedImageIndex = icoOpen
'---add the dummy child node---
.Nodes.Add("")
End With
ParentNode.Nodes.Add(node)
Else
'---this is a normal file---
'---create a new node to be added---
With node
.Text = line.Substring(39)
.ImageIndex = icoPhoto
.SelectedImageIndex = icoPhoto
End With
ParentNode.Nodes.Add(node)
End If
Next
End Sub
Private Sub TreeView1_AfterSelect( _
ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.TreeViewEventArgs) _
Handles TreeView1.AfterSelect
'---always ignore the first "/" char---
Dim FullPath As String = _
ftpServer & e.Node.FullPath.Substring(1).Replace(vbCr, "")
'---display the current folder selected---
If e.Node.ImageIndex <> icoPhoto Then
ToolStripStatusLabel1.Text = FullPath
Return
End If
'---download image---
DownloadImage(FullPath)
End Sub
![]() | |
图 5.FTP服务器的选择目录列表样式,在这种情况下使用MS-DOS样式 . |
'---Download the image from the FTP server---
Private Sub DownloadImage(ByVal path As String)
Try
Dim filename As String = path
Dim ftpReq As FtpWebRequest = WebRequest.Create(filename)
ftpReq.Method = WebRequestMethods.Ftp.DownloadFile
ftpReq.Credentials = New NetworkCredential( _
Username, Password)
ToolStripStatusLabel1.Text = "Downloading image..." & path
Application.DoEvents()
Dim FTPResp As FtpWebResponse = ftpReq.GetResponse
Dim ftpRespStream As Stream = FTPResp.GetResponseStream
PictureBox1.Image = Image.FromStream(ftpRespStream)
FTPResp.Close()
ToolStripStatusLabel1.Text = _
"Downloading image...complete (" & path & ")"
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
- 运用WebRequest 类的Create()方法创造FtpWebRequest 类的实例.Create() 方法采取在URI 参数(包含文本文件下载的网络路径) 。
- 使用FtpWebRequest 的方法属性,设置命令发到FTP服务器,在这种情况下,这个命令是DownloadFile.
- 使用指定的认证登录到FTP服务器.
- 使用ftpwebrequest类中getresponse ()方法从FTP服务器获得回应.
- 使用ftpwebresponse类中getresponsestream()方法,从FTP服务器的响应数据取出流数据.
- 使用Image类的FromStream()方法Use the FromStream() 转成从FTP服务器回应(包含图像)的数据成图像.
您能使用创造文件夹按钮创造一个新目录在FTP 服务器上。选择一个当前的节点增加新文件夹, 然后:
- 用WebRequest 类的Create()方法创造FtpWebRequest 类的实例.Create() 方法采取在URI 参数(含新目录创造的路径).
- 使用FtpWebRequest 的方法属性,设置命令发到FTP服务器,在这种情况下,这个命令是 MakeDirectory.
- 为FTP服务器指定正确的登录证书.
- 运用FtpWebRequest类的GetResponse() 方法从FTP 服务器获得回应数据.
'---Create a new folder---
Private Sub btnCreateFolder_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnCreateFolder.Click
'---ensure user selects a folder---
If TreeView1.SelectedNode.ImageIndex = icoPhoto Then
MsgBox("Please select a folder first.")
Exit Sub
End If
Try
'---formulate the full path for the folder
' to be created---
Dim folder As String = ftpServer & _
TreeView1.SelectedNode.FullPath.Substring(1). _
Replace(vbCr, "") & "/" & txtNewFolderName.Text
Dim ftpReq As FtpWebRequest = WebRequest.Create(folder)
ftpReq.Method = WebRequestMethods.Ftp.MakeDirectory
ftpReq.Credentials = New NetworkCredential( _
Username, Password)
Dim ftpResp As FtpWebResponse = ftpReq.GetResponse
ToolStripStatusLabel1.Text = ftpResp.StatusDescription
ftpResp.Close()
'---refresh the newly added folder---
RefreshCurrentFolder()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
(五邑技术网编译):
当新创建一个文件夹中时,你需要更新TreeView控件来显示新增文件夹. 这是通过refreshcurrentfolder()子程序来执行的:
Private Sub RefreshCurrentFolder()
'---clears all the nodes and...---
TreeView1.SelectedNode.Nodes.Clear()
'---create the nodes again---
BuildDirectory(TreeView1.SelectedNode)
End Sub
删除一个目录
移除(删除)一个目录,选择该文件夹删除,然后:
- 用WebRequest 类的Create()方法创造FtpWebRequest 类的实例.Create() 方法采取在URI 参数(含删除新目录中的路径 ).
- 使用FtpWebRequest 的方法属性,设置命令发到FTP服务器,在这种情况下,这个命令是 RemoveDirectory.
- 为FTP服务器指定正确的登录证书.
- 运用FtpWebRequest类的GetResponse() 方法从FTP 服务器获得回应数据.
Private Sub btnRemoveFolder_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnRemoveFolder.Click
If TreeView1.SelectedNode.ImageIndex = icoPhoto Then
MsgBox("Please select a folder to delete.")
Exit Sub
End If
Try
Dim FullPath As String = ftpServer & _
TreeView1.SelectedNode.FullPath. _
Substring(1).Replace(vbCr, "")
Dim ftpReq As FtpWebRequest = WebRequest.Create(FullPath)
ftpReq.Method = WebRequestMethods.Ftp.RemoveDirectory
ftpReq.Credentials = New NetworkCredential( _
Username, Password)
Dim ftpResp As FtpWebResponse = ftpReq.GetResponse
'---delete current node---
TreeView1.SelectedNode.Remove()
ToolStripStatusLabel1.Text = ftpResp.StatusDescription
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
上传照片
照片上传到FTP服务器,你先选择一个文件夹上传图片, 然后用一个openfiledialog窗口要求用户选择他(她)想要上传的图片. 最后,你单独使用uploadimage()子程序上传的照片(下面定义) :
'---Upload Photos button---
Private Sub btnUploadPhotos_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnUploadPhotos.Click
'---ensure user selects a folder---
If TreeView1.SelectedNode.ImageIndex = icoPhoto Then
MsgBox("Please select a folder to upload the photos.")
Exit Sub
End If
Dim openFileDialog1 As New OpenFileDialog()
With openFileDialog1
.Filter = "jpg files (*.jpg)|*.jpg"
.FilterIndex = 2
.RestoreDirectory = True
.Multiselect = True
End With
'---formulate the full path for the folder
' to be created---
Dim currentSelectedPath As String = _
ftpServer & TreeView1.SelectedNode. _
FullPath.Substring(1). _
Replace(vbCr, "")
'---let user select the photos to upload---
If openFileDialog1.ShowDialog() = _
Windows.Forms.DialogResult.OK Then
'---upload each photo individually---
For i As Integer = 0 To _
openFileDialog1.FileNames.Length - 1
UploadImage(currentSelectedPath & "/" & _
openFileDialog1.FileNames(i). _
Substring(openFileDialog1.FileNames(i). _
LastIndexOf("/") + 1), _
openFileDialog1.FileNames(i))
Next
End If
'---refresh the folder to show the uploaded photos---
RefreshCurrentFolder()
End Sub
该uploadimage()子程序从硬盘上传一张图片到FTP服务器:
- 一,创造webclient类的一个新实例.
- 为FTP服务器指定正确的登录证书
- 使用webclient类uploadfile ( )方法上传文件到FTP服务器. 注意到你需要指定被上传到FTP服务器的文件完整的路径.
'---upload a photo to the FTP server---
Private Sub UploadImage( _
ByVal path As String, ByVal filename As String)
Try
Dim client As New WebClient
client.Credentials = New NetworkCredential( _
Username, Password)
client.UploadFile(path, filename)
ToolStripStatusLabel1.Text = filename & " uploaded!"
Application.DoEvents()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
删除一个图片
要删除图片,先选择一种图片删除. 然后( 五邑技术网编译):
- 用WebRequest 类的Create()方法创造FtpWebRequest 类的实例.Create() 方法采取在URI 参数(含要删除的文件的网络路径).
- 使用FtpWebRequest 的方法属性,设置命令发到FTP服务器,在这种情况下,这个命令是 DeleteFile.
- 为FTP服务器指定正确的登录证书 .
- 运用FtpWebRequest类的GetResponse() 方法从FTP 服务器获得回应数据.
Private Sub btnDeletePhoto_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnDeletePhoto.Click
If TreeView1.SelectedNode.ImageIndex <> icoPhoto Then
MsgBox("Please select a photo to delete.")
Exit Sub
End If
Try
Dim FullPath As String = ftpServer & _
TreeView1.SelectedNode.FullPath. _
Substring(1).Replace(vbCr, "")
Dim ftpReq As FtpWebRequest = WebRequest.Create(FullPath)
ftpReq.Method = WebRequestMethods.Ftp.DeleteFile
ftpReq.Credentials = New NetworkCredential( _
Username, Password)
Dim ftpResp As FtpWebResponse = ftpReq.GetResponse
'---delete the current node---
TreeView1.SelectedNode.Remove()
ToolStripStatusLabel1.Text = ftpResp.StatusDescription
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
一旦图片从FTP服务器删除,你还需要删除它在TreeView控件的节点.
就是这些啦! 现在你可以按F5测试这个应用程序了.
在这篇文章中, 你已看到.NET 2.0中的两个新的管理类的应用: FtpWebRequest 和 FtpWebResponse. 只要有创意, 你就能使用FTP创建出有用的FTP应用程序. 让我知道你正在使用新的FTP类来简单化应用程序开发.
本文由五邑技术网(http://www.wewill.cn)机器+手工翻译,并不保证编译工作的准确性,仅供参考,转载请保留此信息