title: Upload Multiple Files (VB.Net)
body: <p>I'm trying to upload multiple files with VB.Net code but have had no success. I end up with only one file on the webserver when there is more than one file (<code>FileExists</code> is <code>True</code> for multiple elements). If I finish the loop in other some place, it raises an exception.</p>
  
  <p>This is my code:</p>
  
  <pre><code>Imports System.Net
  Imports System.IO
  
  Sub upload()
      Dim filepath As String = IO.Path.Combine(Application.StartupPath, "C:\i.bmp")
      Dim filepath2 As String = IO.Path.Combine(Application.StartupPath, "C:\i.txt")
      Dim url As String = "http://localhost/SEND/MultUp.php"
  
      Dim Element As Object
      Dim sNames(0 To 3) As String 'Array declaration
  
      sNames(0) = filepath2
      sNames(1) = ""
      sNames(2) = ""
      sNames(3) = filepath
  
      Dim boundary As String = IO.Path.GetRandomFileName
      Dim header As New System.Text.StringBuilder()
  
      For Each Element In sNames 'Roaming all elements of array
          If File.Exists(Element) Then
              header.AppendLine("--" &amp; boundary)
              header.Append("Content-Disposition: form-data; name=""files[]"";")
              header.AppendFormat("filename=""{0}""", IO.Path.GetFileName(Element))
              header.AppendLine()
              header.AppendLine("Content-Type: application/octet-stream")
              header.AppendLine()
  
              Dim headerbytes() As Byte = System.Text.Encoding.UTF8.GetBytes(header.ToString)
              Dim endboundarybytes() As Byte = System.Text.Encoding.ASCII.GetBytes(vbNewLine &amp; "--" &amp; boundary &amp; "--" &amp; vbNewLine)
  
              Dim req As Net.HttpWebRequest = Net.HttpWebRequest.Create(url)
              req.ContentType = "multipart/form-data; boundary=" &amp; boundary
              req.ContentLength = headerbytes.Length + New IO.FileInfo(Element).Length + endboundarybytes.Length
              req.Method = "POST"
  
              Dim s As IO.Stream = req.GetRequestStream
              s.Write(headerbytes, 0, headerbytes.Length)
              Dim filebytes() As Byte = My.Computer.FileSystem.ReadAllBytes(Element)
              s.Write(filebytes, 0, filebytes.Length)
              s.Write(endboundarybytes, 0, endboundarybytes.Length)
              s.Close()
  
              header.clear() 'this was missing in my original source code
          End If
      Next
  End Sub
  </code></pre>