I am using the following code to upload files to a FTP, the files get uploaded – the issue is with xls, pdf and video files, they get corrupted. Txt, sql remain intact, i have checked this in the FTP directly. I am thinking its something to do with UTF8.GetBytes? Code is below
Dim URI As String = Url & "/" & fileName
Dim ftp As System.Net.FtpWebRequest = CType(FtpWebRequest.Create(URI), FtpWebRequest)
ftp.Credentials = New System.Net.NetworkCredential(Username, Password)
ftp.Proxy = Nothing
ftp.KeepAlive = False
ftp.UsePassive = False
ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim sourceStream As New StreamReader(file.InputStream)
Dim fileContents As Byte() = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd())
sourceStream.Close()
ftp.ContentLength = fileContents.Length
ftp.UsePassive = True
Dim requestStream As Stream = ftp.GetRequestStream()
requestStream.Write(fileContents, 0, fileContents.Length)
requestStream.Close()
Dim response As FtpWebResponse = DirectCast(ftp.GetResponse(), FtpWebResponse)
Any help would be greatly appreciated.
This is the problem:
You’re reading the stream as a string, as if it’s UTF-8-encoded text, then converting it back to bytes again. Why would you do this? The files in question aren’t UTF-8-encoded text, so you shouldn’t treat them that way.
Read binary data from the stream, never converting it into text unless you’re sure it really is text data. It’s not clear what the type of
fileis here, but hopefully you can get the length without reading the whole thing into memory. You can then use:to copy all the data. Note that you should use
Usingstatements instead of manually closing streams, to avoid leaving them open if exceptions are thrown.