Download file using VB.NET

I use the following code to upload a file to an ftp server:

Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://www.myserver.com/mytextfile.txt"), System.Net.FtpWebRequest)
clsRequest.Credentials = New System.Net.NetworkCredential("user", "pw")
clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile

' read in file...
Dim bFile() As Byte = System.IO.File.ReadAllBytes("C:\text.txt")

' upload file...
Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()
clsStream.Write(bFile, 0, bFile.Length)
clsStream.Close()
clsStream.Dispose()

Anything that easy to download an exe file?
Sheldon LivingstonConsultantAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

käµfm³d 👽Commented:
Sure:
Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://www.myserver.com/mytextfile.txt"), System.Net.FtpWebRequest)
clsRequest.Credentials = New System.Net.NetworkCredential("user", "pw")
clsRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile

' read in file...
Dim bFile() As Byte = System.IO.File.ReadAllBytes("C:\text.txt")

' upload file...
Dim clsStream As System.IO.MemoryStream = DirectCast(clsRequest.GetResponse(), System.Net.FtpWebResponse).GetResponseStream()
Dim outFile As New System.IO.FileStream("C:\your\new\path.txt", IO.FileMode.Create)
clsStream.WriteTo(outFile)

Open in new window

0
käµfm³d 👽Commented:
You can remove lines 5, 6, 7 & 8...  they are irrelevant to the code I posted  :)
0
RameshSCommented:
http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx
Try this code.
 
 
 

' Get the object used to communicate with the server.
        Dim serverUri As Uri = New Uri("ftp://yourftpipaddress/folder")
        Dim request As WebClient = New WebClient()
        'This example assumes the FTP site uses anonymous logon.
        request.Credentials = New NetworkCredential("YourUserID", "Password")
        Try
            Dim newFileData() As Byte = request.DownloadData(serverUri.ToString())
            System.IO.File.WriteAllBytes(@"C:\Temp\yourfilename",newFileData)  
        Catch e As WebException
            MessageBox.Show(e.Message)
        End Try

Open in new window

0
PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

Sheldon LivingstonConsultantAuthor Commented:
The code is crashing at

Dim clsStream As System.IO.MemoryStream = DirectCast(clsRequest.GetResponse(), System.Net.FtpWebResponse).GetResponseStream()

with the error of

A first chance exception of type 'System.Net.WebException' occurred in System.dll

Is this because it is an exe file?
0
käµfm³d 👽Commented:
"First chance" exceptions don't cause applications to crash that I'm aware of--this is the runtime handling the exception for you. Are you getting a different exception?
0
Sheldon LivingstonConsultantAuthor Commented:
Well... the exe isn't downloading...
0
käµfm³d 👽Commented:
It's more than likely the implicit cast to MemoryStream that I gave. This should be better:
Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://www.myserver.com/mytextfile.txt"), System.Net.FtpWebRequest)
clsRequest.Credentials = New System.Net.NetworkCredential("user", "pw")
clsRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile

' read in file...
Dim bFile() As Byte = System.IO.File.ReadAllBytes("C:\text.txt")

' upload file...
Dim clsStream As System.IO.Stream = DirectCast(clsRequest.GetResponse(), System.Net.FtpWebResponse).GetResponseStream()
Dim outFile As New System.IO.FileStream("C:\your\new\path.txt", IO.FileMode.Create)
Dim str As New System.IO.MemoryStream()
Dim buffer(clsStream.Length) As Byte

str.Read(buffer, 0, buffer.Length)
str.WriteTo(outFile)

Open in new window

0
Sheldon LivingstonConsultantAuthor Commented:
Closer!  Now I get a 0kb file with the correct file name.
0
käµfm³d 👽Commented:
Sorry...   forgot to close the stream  !!!   Doh!!!
Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://www.myserver.com/mytextfile.txt"), System.Net.FtpWebRequest)
clsRequest.Credentials = New System.Net.NetworkCredential("user", "pw")
clsRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile

' read in file...
Dim bFile() As Byte = System.IO.File.ReadAllBytes("C:\text.txt")

' upload file...
Dim clsStream As System.IO.Stream = DirectCast(clsRequest.GetResponse(), System.Net.FtpWebResponse).GetResponseStream()
Dim outFile As New System.IO.FileStream("C:\your\new\path.txt", IO.FileMode.Create)
Dim str As New System.IO.MemoryStream()
Dim buffer(clsStream.Length) As Byte

str.Read(buffer, 0, buffer.Length)
str.WriteTo(outFile)

' This should flush the buffer to write the data to the file.
outFile.Close()
str.Close()
clsStream.Close()

Open in new window

0
Sheldon LivingstonConsultantAuthor Commented:
Same thing...

Issue seems to be:

Dim buffer(clsStream.Length) As Byte

0
käµfm³d 👽Commented:
Ok...  that's what I get for shooting from the hip  :(

I didn't have access to a site for the earlier posts, but I tested the following with the address/file shown. Please replace the appropriate file & username/pass for you application:
Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://ftp.2600.com/.banner"), System.Net.FtpWebRequest)
clsRequest.Credentials = New System.Net.NetworkCredential("anonymous", "guest@unkown.com")
clsRequest.Method = System.Net.WebRequestMethods.Ftp.DownloadFile

Dim response As System.Net.FtpWebResponse = DirectCast(clsRequest.GetResponse(), System.Net.FtpWebResponse)
Dim clsStream As System.IO.Stream = response.GetResponseStream()
Dim outFile As New System.IO.FileStream("path.txt", IO.FileMode.Create)
Dim data(512) As Byte
Dim bytesRead As Integer

Do
    bytesRead = clsStream.Read(data, 0, data.Length)

    If bytesRead >= 0 Then
        outFile.Write(data, 0, bytesRead)
    End If
Loop While bytesRead > 0


' This should flush the buffer to write the data to the file.
outFile.Close()
clsStream.Close()

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
RameshSCommented:
I have tested the below code to download a file from ftp server to your local PC.

Try it. Enter the ftp server ip, folder and file name details, user id and password in the code.






Imports System.Net

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim serverUri As Uri = New Uri("ftp://YourFtpIPAddress/FolderName/Test1.txt")
        Dim request As WebClient = New WebClient()
        request.Credentials = New NetworkCredential("FtpUserId", "FtpPassword")
        request.Proxy = Nothing

        Try
            Dim newFileData() As Byte = request.DownloadData(serverUri.ToString())
            System.IO.File.WriteAllBytes("D:\Temp\Test1.txt", newFileData)
        Catch ex As WebException
            MessageBox.Show(ex.Message)
        End Try
    End Sub
End Class

Open in new window

0
Wayne Taylor (webtubbs)Commented:
What about this?

        Dim wc As New System.Net.WebClient()
        wc.Credentials = New System.Net.NetworkCredential("user", "pw")
        wc.DownloadFile("ftp://www.myserver.com/mytextfile.txt", "C:\text.txt")

Wayne
0
Sheldon LivingstonConsultantAuthor Commented:
Sweet!  Can't believe you got it as far as you did "from the hip".  Well done.

Thank you.
0
käµfm³d 👽Commented:
NP. Sorry it took so many posts, but glad to help nonetheless   :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.