Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

How to upload a file

2009-09-17

First I must mention that this is my first ever blog post using Windows Live Writer. The topic was inspired by a question that was raised on the MSDN forums. How do I upload a file, and how can I control the remote filename? This is how it could be done:

'The full path to the source file.
Dim Source As String = "C:\MyFiles\SourceFile.txt"

'The full destination path (will be created).
Dim Destination As String = "ftp://www.myserver.com/myfolder/destination.txt"

'Use the static (shared) method Create to create a web request.
'Pass the destination as an argument, and cast it to a FtpWebRequest.
Dim R As System.Net.FtpWebRequest = CType(System.Net.WebRequest.Create(Destination), _
System.Net.FtpWebRequest)

'Tell the request how it will login (using a NetworkCredential object)
R.Credentials = New System.Net.NetworkCredential("myUsername", "P@ssw0rd")

'...and what kind of method it will represent. A file upload.
R.Method = System.Net.WebRequestMethods.Ftp.UploadFile

'Here I use the simplest method I can imagine to get the
'bytes from the file to an byte array.
Dim FileContens() As Byte = System.IO.File.ReadAllBytes(Source)

'Finaly, I put the bytes on the request stream.
Using S As System.IO.Stream = R.GetRequestStream()
   S.Write(FileContens, 0, FileContens.Length)
   S.Close()
End Using

You could increase the level of control by replacing the ReadAllBytes call with some own code to read the bytes. This might be interesting if you’re for example are handling larger files, and want to show progress. To give away all control, you can use the already build function My.Computer.Network.UploadFile.

Categories: General, Visual Basic 8

Tags: FTP

Leave a Reply

Your email address will not be published. Required fields are marked *



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips