dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Build a Photo Viewer Using the New FTP Classes in .NET 2.0 : Page 2

Yet another highly useful but underappreciated feature of .NET 2.0? How about the FTPWebRequest and FtpWebResponse classes? These nifty classes let you built FTP file access right into your applications. See how it's done with this handy photo viewer example.


advertisement
Creating a New Directory
You can create a new directory on the FTP server by using the Create Folder button. To do so, select a current node to add the new folder, then:
  • Create an instance of the FtpWebRequest class using the Create() method of the WebRequest class. The Create() method takes in a URI parameter (containing the path of the new directory to create).
  • Set the command to be sent to the FTP server using the Method property of the FtpWebRequest class; in this case this command is MakeDirectory.
  • Specify the login credential to the FTP server.
  • Obtain the response from the FTP server using the GetResponse() method from the FtpWebRequest class.

    '---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
When a new folder is created, you need to update the TreeView control to reflect the newly added folder. This is accomplished by the RefreshCurrentFolder() subroutine:

    Private Sub RefreshCurrentFolder()
        '---clears all the nodes and...---
        TreeView1.SelectedNode.Nodes.Clear()
        '---create the nodes again---
        BuildDirectory(TreeView1.SelectedNode)
    End Sub
Removing a Directory
To remove (delete) a directory, select the folder to delete and then:
  • Create an instance of the FtpWebRequest class using the Create() method of the WebRequest class. The Create() method takes in a URI parameter (containing the path of the new directory to remove).
  • Set the command to be sent to the FTP server using the Method property of the FtpWebRequest class; in this case the command is RemoveDirectory.
  • Specify the login credential to the FTP server.
  • Obtain the response from the FTP server using the GetResponse() method from the FtpWebRequest class.

    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
Note that if a directory is not empty (that is, it contains files and subdirectories), the deletion process will fail. You will need to remove its content first before removing the directory.

Uploading Photos
To upload photos to the FTP server, you first select a folder to upload the photos to, and then use an OpenFileDialog window to ask the user to select the photo(s) he wants to upload. Finally, you upload the photos individually using the UploadImage() subroutine (defined next):


    '---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
The UploadImage() subroutine uploads a photo from the hard disk to the FTP server:
  • First, create a new instance of the WebClient class.
  • Specify the login credential to the FTP server
  • Upload the file to the FTP server using the UploadFile() method from the WebClient class. Note that you need to specify the full pathname of the file to be uploaded to the FTP server.

    '---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
Deleting a Photo
To delete a photo, first select a photo to delete. Then:
  • Create an instance of the FtpWebRequest class using the Create() method of the WebRequest class. The Create() method takes in a URI parameter (containing the path for the file to be removed).
  • Set the command to be sent to the FTP server using the Method property of the FtpWebRequest class; in this case the command is DeleteFile.
  • Specify the login credential to the FTP server.
  • Obtain the response from the FTP server using the GetResponse() method from the FtpWebRequest class.

    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
Once the photo is removed from the FTP server, you also need to delete its node in the TreeView control.

That's it! You can now test the application by pressing F5.

In this article, you have seen the usefulness of the two new managed classes in .NET 2.0: FtpWebRequest and FtpWebResponse. With some creativity, you can create useful applications using FTP. Let me know how you are using the new FTP class to simplify your application development.



Wei-Meng Lee is a Microsoft MVP and founder of Developer Learning Solutions, a technology company specializing in hands-on training on the latest Microsoft technologies. He is an established developer and trainer specializing in .NET and wireless technologies. Wei-Meng speaks regularly at international conferences and has authored and coauthored numerous books on .NET, XML, and wireless technologies. He writes extensively on topics ranging from .NET to Mac OS X. He is also the author of the .NET Compact Framework Pocket Guide, ASP.NET 2.0: A Developer's Notebook (both from O'Reilly Media, Inc.), and Programming Sudoku (Apress). Here is Wei-Meng's blog.
Thanks for your registration, follow us on our social networks to keep up-to-date