Search code examples
.netvb.netftpftp-clientftpwebrequest

Upload file contents from ListBox to FTP


To read a file contents to ListBox, I used DownloadFile method from my previous question
Loading file contents from FTP to ListBox

Dim request As FtpWebRequest = 
    WebRequest.Create("ftp://example.com/path/Ann.txt")
request.Method = WebRequestMethods.Ftp.DownloadFile
request.Credentials = New NetworkCredential("username", "password")

Using response As FtpWebResponse = request.GetResponse(),
      stream As Stream = response.GetResponseStream(),
      reader As StreamReader = New StreamReader(stream)
    While Not reader.EndOfStream
        ListBox1.Items.Add(reader.ReadLine())
    End While
End Using

Now I want to add another button that uses StreamWriter and WebRequest.GetRequestStream to upload the contents of ListBox back to FTP.


Solution

  • You basically need the code from my answer to
    How to download file from FTP and upload it again.


    Though to easily copy contents (lines) of ListBox, you can slightly modify it to write line-by-line using StreamWriter:

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim request As FtpWebRequest =
            WebRequest.Create("ftp://example.com/path/Ann.txt")
        request.Method = WebRequestMethods.Ftp.UploadFile
        request.Credentials = New NetworkCredential("username", "password")
        request.UseBinary = False
    
        Using stream As Stream = request.GetRequestStream(),
              writer As StreamWriter = New StreamWriter(stream)
            For index As Integer = 0 To ListBox1.Items.Count - 1
                writer.WriteLine(ListBox1.Items(index))
            Next
        End Using
    End Sub