FTP upload ProgressBar in VB.NET - vb.net

I'm coding an application that uploads a file to a remote FTP server. This is my code that already works.
clsrequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim bFile() As Byte = System.IO.File.ReadAllBytes(rutaorigen)
Dim clsStream As System.IO.Stream = clsrequest.GetRequestStream()
clsStream.Write(bFile, 0, bFile.Length)
clsStream.Close()
clsStream.Dispose()
Now I want to show the progress in a ProgressBar in VB.NET.
Files are not too big (10 MB max).
I've already tried an example that I found here, but it didn't work.
I hope you can help me. Thanks!

Simple progress on console:
Dim request As WebRequest = WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip")
request.Credentials = New NetworkCredential("username", "password")
request.Method = WebRequestMethods.Ftp.UploadFile
Using fileStream As Stream = File.OpenRead("C:\local\path\file.zip"),
ftpStream As Stream = request.GetRequestStream()
Dim buffer As Byte() = New Byte(10240 - 1) {}
Dim read As Integer
Do
read = fileStream.Read(buffer, 0, buffer.Length)
If read > 0 Then
ftpStream.Write(buffer, 0, read)
Console.WriteLine("Uploaded {0} bytes", fileStream.Position)
End If
Loop While read > 0
End Using
WinForms GUI progress:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Run Upload on background thread
Task.Run((Sub() Upload()))
End Sub
Sub Upload()
Dim request As WebRequest =
WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip")
request.Credentials = New NetworkCredential("username", "password")
request.Method = WebRequestMethods.Ftp.UploadFile
Using fileStream As Stream = File.OpenRead("C:\local\path\file.zip"),
ftpStream As Stream = request.GetRequestStream()
ProgressBar1.Invoke(Sub() ProgressBar1.Maximum = fileStream.Length)
Dim buffer As Byte() = New Byte(10240 - 1) {}
Dim read As Integer
Do
read = fileStream.Read(buffer, 0, buffer.Length)
If read > 0 Then
ftpStream.Write(buffer, 0, read)
ProgressBar1.Invoke(Sub() ProgressBar1.Value = fileStream.Position)
End If
Loop While read > 0
End Using
End Sub

I got this from an example a long time ago. The code should be fairly easy to change for your needs.
Dim clsRequest As System.Net.FtpWebRequest = _
DirectCast(System.Net.WebRequest.Create(ServLabel.Text & TextBox1.Text), System.Net.FtpWebRequest)
clsRequest.Credentials = New System.Net.NetworkCredential(PassLabel.Text, UserLabel.Text)
clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
rfshTMR.Enabled = True
Dim File() As Byte = System.IO.File.ReadAllBytes(txtFile.Text)
Dim clsStream As System.IO.Stream = _
clsRequest.GetRequestStream()
clsStream.Write(File, 0, File.Length)
For offset As Integer = 0 To File.Length Step 1024
ToolStripProgressBar1.Value = CType(offset * ToolStripProgressBar1.Maximum / File.Length, Integer)
Dim chunkSize As Integer = File.Length - offset - 1
If chunkSize > 1024 Then chunkSize = 1024
clsStream.Write(File, offset, chunkSize)
ToolStripProgressBar1.Value = ToolStripProgressBar1.Maximum
Next
clsStream.Close()
clsStream.Dispose()
MsgBox("File Is Now In Database", MsgBoxStyle.OkOnly, "Upload Complete")

Related

VB.NET FTP Downloaded file corrupt

I want to download all file that located on FTP site. I break into 2 operations. First is to get the list of all files in the directory. Then I proceed to second which download each file. But unfortunately, the downloaded file is corrupt. Worst over, it affect the file on FTP folder. Both folder contains corrupt file. From a viewing thumbnails image to default image thumbnails. How this happen and to overcome this? Below are my code; full code class. I provide as reference and guide to do a correct way :)
Private strTargetPath As String
Private strDestPath As String
Private Sub frmLoader_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
objSQL = New clsSQL
If objSQL.SQLGetAllData Then 'Get data from SQL and insert into an arraylist
strTargetPath = "ftp://192.168.1.120/image/"
strDestPath = "D:\Application\FTPImg\"
ListFileFromFTP()
End If
Catch ex As Exception
strErrMsg = "Oops! Something is wrong with loading login form."
MessageBox.Show(strErrMsg & vbCrLf & "ExMsg: " & ex.Message, "Error message!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub ListFileFromFTP()
Dim arrFile As ArrayList
Dim strPath As String
Try
Dim reqFTP As FtpWebRequest
reqFTP = FtpWebRequest.Create(New Uri(strTargetPath))
reqFTP.UseBinary = True
reqFTP.Credentials = New NetworkCredential("user", "user123")
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory
reqFTP.Proxy = Nothing
reqFTP.KeepAlive = False
reqFTP.UsePassive = False
Dim response As FtpWebResponse = DirectCast(reqFTP.GetResponse(), FtpWebResponse)
Dim sr As StreamReader
sr = New StreamReader(reqFTP.GetResponse().GetResponseStream())
Dim FileListing As String = sr.ReadLine
arrFile = New ArrayList
While FileListing <> Nothing
strPath = strTargetPath & FileListing
arrFile.Add(strPath)
FileListing = sr.ReadLine
End While
sr.Close()
sr = Nothing
reqFTP = Nothing
response.Close()
For i = 0 To (arrFile.Count - 1)
DownloadImage(arrFile.Item(i))
Next
Catch ex As Exception
strErrMsg = "Oops! Something is wrong with ListFileFromFTP."
MessageBox.Show(strErrMsg & vbCrLf & "ExMsg: " & ex.Message, "Error message!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Public Function DownloadImage(ByVal strName As String) As String
Dim ftp_request As FtpWebRequest = Nothing
Dim ftpStream As Stream = Nothing
Dim strOldName As String
Dim strNewName As String
Dim withoutextension As String
Dim extension As String
Try
strOldName = strTargetPath & strName
withoutextension = Path.GetFileNameWithoutExtension(strOldName)
extension = Path.GetExtension(strOldName)
strNewName = strDestPath & withoutextension & extension
ftp_request = CType(System.Net.FtpWebRequest.Create(strName), System.Net.FtpWebRequest)
ftp_request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
ftp_request.Credentials = New System.Net.NetworkCredential("user", "user123")
ftp_request.UseBinary = True
ftp_request.KeepAlive = False
ftp_request.Proxy = Nothing
Dim response As FtpWebResponse = DirectCast(ftp_request.GetResponse(), FtpWebResponse)
Dim responseStream As IO.Stream = response.GetResponseStream
Dim fs As New IO.FileStream(strNewName, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Do
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0
responseStream.Close()
fs.Flush()
fs.Close()
responseStream.Close()
response.Close()
Catch ex As WebException
Dim response As FtpWebResponse = ex.Response
If response.StatusCode = FtpStatusCode.ActionNotTakenFileUnavailable Then
MsgBox(response.StatusDescription)
Return String.Empty
Else
MsgBox(response.StatusDescription)
End If
End Try
End Function
For download file, this is the right code that succeed:
Private Sub Download(ByVal strFTPPath As String)
Dim reqFTP As FtpWebRequest = Nothing
Dim ftpStream As Stream = Nothing
Try
Dim outputStream As New FileStream(strDestPath & strImgName, FileMode.Create)
reqFTP = DirectCast(FtpWebRequest.Create(New Uri(strFTPPath)), FtpWebRequest)
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile
reqFTP.UseBinary = True
reqFTP.Credentials = New NetworkCredential("user", "user123")
Dim response As FtpWebResponse = DirectCast(reqFTP.GetResponse(), FtpWebResponse)
ftpStream = response.GetResponseStream()
Dim cl As Long = response.ContentLength
Dim bufferSize As Integer = 2048
Dim readCount As Integer
Dim buffer As Byte() = New Byte(bufferSize - 1) {}
readCount = ftpStream.Read(buffer, 0, bufferSize)
While readCount > 0
outputStream.Write(buffer, 0, readCount)
readCount = ftpStream.Read(buffer, 0, bufferSize)
End While
ftpStream.Close()
outputStream.Close()
response.Close()
Catch ex As Exception
If ftpStream IsNot Nothing Then
ftpStream.Close()
ftpStream.Dispose()
End If
Throw New Exception(ex.Message.ToString())
End Try
End Sub
There is something strange in your code. You are closing the responseStream twice.
And you are using ftp request method uploadFile. But then downloading it.
Instead of using the ftp stuff use this instead. Its much more simple and your outsourcing the buffers and streams to microsoft, which should be less buggy than us.
Dim webClient = new WebClient()
webClient.Credentials = new NetworkCredential("user", "user123")
dim response = webClient.UploadFile("ftp://MyFtpAddress","c:\myfile.jpg")
dim sResponse = System.Text.Encoding.Default.GetString(response)

Compression to stream

I'm attempting to compress a file to stream which is sent over wcf and decompressed. However with the following code the I'm get not a valid exe when attempting to execute the decompressed exe. Any decompressed exe is around 211-212 bytes lower that the original.
Sub Main()
Dim strm As Stream = CompressToStream("c:\rje\Launcher.exe")
DecompressToFile(strm)
End Sub
Compression Routine
Private Function CompressToStream(ByVal strFullFilename As String) As Stream
If File.Exists(strFullFilename) Then
Dim uncompressedfile As New MemoryStream(File.ReadAllBytes(strFullFilename))
Dim compressedStream As New MemoryStream
Dim compressionStream As New GZipStream(compressedStream, CompressionMode.Compress)
uncompressedfile.CopyToStream(compressionStream)
compressionStream.Flush()
compressedStream.Position = 0
Return compressedStream
End If
Return Nothing
End Function
Extension method to copy streams as using .net3.5
<System.Runtime.CompilerServices.Extension()> _
Private Sub CopyToStream(ByVal input As Stream, ByRef output As Stream)
Dim Buffer(4096) As Byte
Dim numRead As Integer = input.Read(Buffer, 0, Buffer.Length)
Do While numRead <> 0
output.Write(Buffer, 0, numRead)
numRead = input.Read(Buffer, 0, Buffer.Length)
Loop
End Sub
Finally Decompression
Private Sub DecompressToFile(ByVal strmDownload As Stream)
Dim spath As String = "c:\rje\text.exe"
Using outFile As FileStream = File.Create(spath)
Using Decompress As GZipStream = New GZipStream(strmDownload, CompressionMode.Decompress)
' Copy the compressed file into the decompression stream.
Dim buffer(4096) As Byte
Dim numRead As Integer = Decompress.Read(buffer, 0, buffer.Length)
Do While numRead <> 0
outFile.Write(buffer, 0, numRead)
numRead = Decompress.Read(buffer, 0, buffer.Length)
Loop
End Using
outFile.Close()
End Using
End Sub
If someone could point out where I'm going wrong that would be great.
The error was with CompressToStream, amending as follows functions correctly
Private Function CompressToStream(ByVal strFullFilename As String) As Stream
If File.Exists(strFullFilename) Then
Dim compressedStream As New MemoryStream()
Using uncompressedfile As New MemoryStream(File.ReadAllBytes(strFullFilename))
Using compressionStream As New GZipStream(compressedStream, CompressionMode.Compress, True)
uncompressedfile.CopyToStream(compressionStream)
End Using
End Using
compressedStream.Seek(0, SeekOrigin.Begin)
Return compressedStream
End If
Return Nothing
End Function
I still don't have an answer as to why I shouldn't use File.Exists()?
Here are adapted Compress()/Decompress() methods from the sample in the link I posted in my comment:
Private Function Compress(ByVal strFullFilename As FileInfo) As Stream
' Get the stream of the source file.
Dim fi as New FileInfo(strFullFilename)
Dim result As New MemoryStream()
Using inFile As FileStream = fi.OpenRead()
' Compressing:
' Prevent compressing hidden and already compressed files.
If (File.GetAttributes(fi.FullName) And FileAttributes.Hidden) _
<> FileAttributes.Hidden And fi.Extension <> ".gz" Then
' Create the compressed file.
Using Compress As GZipStream = New GZipStream(result, CompressionMode.Compress)
' Copy the source file into the compression stream.
Dim buffer As Byte() = New Byte(4096) {}
Dim numRead As Integer = inFile.Read(buffer, 0, buffer.Length)
Do While numRead <> 0
Compress.Write(buffer, 0, numRead)
numRead = inFile.Read(buffer, 0, buffer.Length)
Loop
'Console.WriteLine("Compressed {0} from {1} to {2} bytes.", fi.Name, fi.Length.ToString(), result.Length.ToString())
End Using
End If
End Using
Return result
End Sub
' Method to decompress.
Private Sub Decompress(ByVal strmDownload As Stream, ByVal resultFileName As String)
' Create the decompressed file.
Using outFile As FileStream = File.Create(resultFileName)
Using Decomp As GZipStream = New GZipStream(strmDownload, CompressionMode.Decompress)
' Copy the compressed file into the decompression stream.
Dim buffer As Byte() = New Byte(4096) {}
Dim numRead As Integer = Decompress.Read(buffer, 0, buffer.Length)
Do While numRead <> 0
outFile.Write(buffer, 0, numRead)
numRead = Decomp.Read(buffer, 0, buffer.Length)
Loop
'Console.WriteLine("Decompressed: {0}", fi.Name)
End Using
End Using
End Using
End Sub

Read MemoryStream - load image \ byte and read it

ok i have image that i bind info in it and i want to read the info
now from file (FileStream) its work
but i want to do it not from file so i need to use MemoryStream
here the example that work and how i do it now how i make it work with MemoryStream (with byte = My.Resources or PictureBox1.image)
Using FS As New IO.FileStream(image, IO.FileMode.Open)
FS.Seek(0, IO.SeekOrigin.End)
While Not FS.ReadByte = Asc("|")
FS.Position -= 2
End While
Dim s As String = Nothing
While Not FS.Position = FS.Length - 4
s &= Chr(FS.ReadByte.ToString)
End While
Dim Ext As String = Nothing
FS.Seek(0, IO.SeekOrigin.End)
While Not FS.ReadByte = Asc("*")
FS.Position -= 2
End While
While Not FS.Position = FS.Length
Ext &= Chr(FS.ReadByte.ToString)
End While
FS.Seek(FS.Length - ((s.Length + s) + 5), IO.SeekOrigin.Begin)
While Not FS.Position = FS.Length - (s.Length + 5)
Dim Data As Byte() = New Byte(FS.Position) {}
FS.Read(Data, 0, Data.Length)
FS.Close()
End While
at the end save the byte to file
i try to use it like this
Using FS As New IO.MemoryStream(image) 'image = byte()
but not work
how i can do it read it again in memory
thanks
This will convert a ByteArray to MemoryStream to Image
Public Function byteArrayToImage(byteArrayIn As Byte()) As Image
Dim ms As New MemoryStream(byteArrayIn)
Dim returnImage As Image = Image.FromStream(ms)
Return returnImage
End Function

VB.NET - download zip in Memory and extract file from memory to disk

I'm having some trouble with this, despite finding examples. I think it may be an encoding problem, but I'm just not sure. I am trying to programitally download a file from a https server, that uses cookies (and hence I'm using httpwebrequest). I'm debug printing the capacity of the streams to check, but the output [raw] files look different. Have tried other encoding to no avail.
Code:
Sub downloadzip(strURL As String, strDestDir As String)
Dim request As HttpWebRequest
Dim response As HttpWebResponse
request = Net.HttpWebRequest.Create(strURL)
request.UserAgent = strUserAgent
request.Method = "GET"
request.CookieContainer = cookieJar
response = request.GetResponse()
If response.ContentType = "application/zip" Then
Debug.WriteLine("Is Zip")
Else
Debug.WriteLine("Is NOT Zip: is " + response.ContentType.ToString)
Exit Sub
End If
Dim intLen As Int64 = response.ContentLength
Debug.WriteLine("response length: " + intLen.ToString)
Using srStreamRemote As StreamReader = New StreamReader(response.GetResponseStream(), Encoding.Default)
'Using ms As New MemoryStream(intLen)
Dim fullfile As String = srStreamRemote.ReadToEnd
Dim memstream As MemoryStream = New MemoryStream(New UnicodeEncoding().GetBytes(fullfile))
'test write out to flie
Dim data As Byte() = memstream.ToArray()
Using filestrm As FileStream = New FileStream("c:\temp\debug.zip", FileMode.Create)
filestrm.Write(data, 0, data.Length)
End Using
Debug.WriteLine("Memstream capacity " + memstream.Capacity.ToString)
'Dim strData As String = srStreamRemote.ReadToEnd
memstream.Seek(0, 0)
Dim buffer As Byte() = New Byte(2048) {}
Using zip As New ZipInputStream(memstream)
Debug.WriteLine("zip stream cap " + zip.Length.ToString)
zip.Seek(0, 0)
Dim e As ZipEntry
Dim flag As Boolean = True
Do While flag ' daft, but won't assign e=zip... tries to evaluate
e = zip.GetNextEntry
If IsNothing(e) Then
flag = False
Exit Do
Else
e.UseUnicodeAsNecessary = True
End If
If Not e.IsDirectory Then
Debug.WriteLine("Writing out " + e.FileName)
' e.Extract(strDestDir)
Using output As FileStream = File.Open(Path.Combine(strDestDir, e.FileName), _
FileMode.Create, FileAccess.ReadWrite)
Dim n As Integer
Do While (n = zip.Read(buffer, 0, buffer.Length) > 0)
output.Write(buffer, 0, n)
Loop
End Using
End If
Loop
End Using
'End Using
End Using 'srStreamRemote.Close()
response.Close()
End Sub
So I get the right size file downloaded, but dotnetzip does not recognise it, and the files that get copied out are incomplete/invalid zips. I've spent most of today on this, and am ready to give up.
I think the answer will be to break down the problem, and perhaps change a couple aspects in the code.
For example, lets get rid of converting the response stream to a string:
Dim memStream As MemoryStream
Using rdr As System.IO.Stream = response.GetResponseStream
Dim count = Convert.ToInt32(response.ContentLength)
Dim buffer = New Byte(count) {}
Dim bytesRead As Integer
Do
bytesRead += rdr.Read(buffer, bytesRead, count - bytesRead)
Loop Until bytesRead = count
rdr.Close()
memStream = New MemoryStream(buffer)
End Using
Next, there's an easier way to output the contents of a memory stream to a file. Consider your code
Dim data As Byte() = memstream.ToArray()
Using filestrm As FileStream = New FileStream("c:\temp\debug.zip", FileMode.Create)
filestrm.Write(data, 0, data.Length)
End Using
can be replaced with
Using filestrm As FileStream = New FileStream("c:\temp\debug.zip", FileMode.Create)
memstream.WriteTo(filestrm)
End Using
That eliminates the need to transfer your memory stream into another byte array, and then push the byte array down the stream, when in fact the memory stream can transfer data directly to file (via the filestream) saving the middle-man buffer.
I'll admit I haven't worked with the Zip/compression libraries you're using, but with the above amendments you have removed unnecessary transfers between streams, byte arrays, strings, etc, and hopefully eliminated the encoding issues you were having.
Give that a try and let us know how you get on. Consider attempting to open the file that you saved ("C:\temp\debug.zip") to see if it is listed as corrupt. If not, then you know at least as far as that in the code, it is working ok.
I thought I'd post my full working solution to my own question, it combines the two excellent replies I've had, thank you guys.
Sub downloadzip(strURL As String, strDestDir As String)
Try
Dim request As HttpWebRequest
Dim response As HttpWebResponse
request = Net.HttpWebRequest.Create(strURL)
request.UserAgent = strUserAgent
request.Method = "GET"
request.CookieContainer = cookieJar
response = request.GetResponse()
If response.ContentType = "application/zip" Then
Debug.WriteLine("Is Zip")
Else
Debug.WriteLine("Is NOT Zip: is " + response.ContentType.ToString)
Exit Sub
End If
Dim intLen As Int32 = response.ContentLength
Debug.WriteLine("response length: " + intLen.ToString)
Dim memStream As MemoryStream
Using stmResponse As IO.Stream = response.GetResponseStream()
'Using ms As New MemoryStream(intLen)
Dim buffer = New Byte(intLen) {}
'Dim memstream As MemoryStream = New MemoryStream(buffer)
Dim bytesRead As Integer
Do
bytesRead += stmResponse.Read(buffer, bytesRead, intLen - bytesRead)
Loop Until bytesRead = intLen
memStream = New MemoryStream(buffer)
Dim res As Boolean = False
res = ZipExtracttoFile(memStream, strDestDir)
End Using 'srStreamRemote.Close()
response.Close()
Catch ex As Exception
'to do :)
End Try
End Sub
Function ZipExtracttoFile(strm As MemoryStream, strDestDir As String) As Boolean
Try
Using zip As ZipFile = ZipFile.Read(strm)
For Each e As ZipEntry In zip
e.Extract(strDestDir)
Next
End Using
Catch ex As Exception
Return False
End Try
Return True
End Function
You can download into a MemoryStream, then examine it:
Public Sub Download(url as String)
Dim req As HttpWebRequest = System.Net.WebRequest.Create(url)
req.Method = "GET"
Dim resp As HttpWebResponse = req.GetResponse()
If resp.ContentType = "application/zip" Then
Console.Error.Write("The result is a zip file.")
Dim length As Int64 = resp.ContentLength
If length = -1 Then
Console.Error.WriteLine("... length unspecified")
length = 16 * 1024
Else
Console.Error.WriteLine("... has length {0}", length)
End If
Dim ms As New MemoryStream
CopyStream(resp.GetResponseStream(), ms) '' **see note below!!!!
'' list contents of the zip file
ms.Seek(0,SeekOrigin.Begin)
Using zip As ZipFile = ZipFile.Read (ms)
Dim e As ZipEntry
Console.Error.WriteLine("Entries:")
Console.Error.WriteLine(" {0,22} {1,10} {2,12}", _
"Name", "compressed", "uncompressed")
Console.Error.WriteLine("----------------------------------------------------")
For Each e In zip
Console.Error.WriteLine(" {0,22} {1,10} {2,12}", _
e.FileName, _
e.CompressedSize, _
e.UncompressedSize)
Next
End Using
Else
Console.Error.WriteLine("The result is Not a zip file.")
CopyStream(resp.GetResponseStream(), Console.OpenStandardOutput)
End If
End Sub
Private Shared Sub CopyStream(input As Stream, output As Stream)
Dim buffer(32768 - 1) As Byte
Dim n As Int32
Do
n = input.Read(buffer, 0, buffer.Length)
If n = 0 Then Exit Do
output.Write(buffer, 0, n)
Loop
End Sub
EDIT
Just one note - I would not advise using this code (this approach) if the Zip file is very large. How large is "very large"? Well that depends, of course. The code I suggested above downloads the file into a memory stream, which of course means the entire contents of the zip file are held in memory. If it is a 28kb zip file, then there's no problem. But if it is a 2gb zip file, then you may have a big problem.
In that case you will want to stream it to a temporary file on disk, not to a MemoryStream. I'll leave that as an exercise for the reader.
The above will work for "reasonably sized" zip files, where "reasonable" depends on your machine configuration and application scenario.

ftp upload of multiple large files into one file

I am trying to upload 2 large files to a ftp server by uploading as one file to a location. I have it working if the files are small but it crashes with large files.
For i As Integer = 0 To filelist.Count() - 1
Dim fRequest As FtpWebRequest = WebRequest.Create(ftpPath & "/Reports/" & filelist.Item(i))
fRequest.Credentials = New NetworkCredential(username, psswd)
fRequest.KeepAlive = False
fRequest.Proxy = Nothing
fRequest.UsePassive = True
fRequest.UseBinary = True
fRequest.Method = WebRequestMethods.Ftp.DownloadFile
fRequest.Timeout = 30000
Try
' read in file...
' upload file...
Dim fresponse As FtpWebResponse = DirectCast(fRequest.GetResponse(), FtpWebResponse)
Dim fstream As FileStream = fileobj.OpenRead()
Dim sStream As Stream = fRequest.GetRequestStream()
Dim reader As New StreamReader(fstream)
swriter.WriteLine(reader.ReadToEnd)
swriter.Flush()
fstream.Close()
fRequest.Abort()
Catch ex As Exception
appLogs.constructLog(ex.Message.ToString & " # ", True, True)
errorReporting(ex.Message.ToString & fileItem)
End Try
Next
swriter.Close()
swriter.Dispose()
The Below actually works and i can finally upload 10gb + files
Dim bytesread As Byte = 0
Dim buffer As Integer = 2
Dim fRequest As FtpWebRequest = WebRequest.Create(UPloaddir & "/" & filenameup & ".bak")
' fRequest.Credentials = New NetworkCredential(username, psswd)
fRequest.KeepAlive = False
fRequest.Proxy = Nothing
fRequest.UsePassive = True
fRequest.UseBinary = False
fRequest.Method = WebRequestMethods.Ftp.UploadFile
fRequest.Timeout = 180000
' Try
' read in file...
Dim fs As FileStream = File.OpenRead(folder & "\" & fi.Name)
Dim bFile As Byte() = New Byte(1) {}
Dim fstream As Stream = fRequest.GetRequestStream
' upload file...
Do
bytesread = fs.Read(bFile, 0, buffer)
fstream.Write(bFile, 0, bFile.Length)
Loop Until bytesread = 0
fstream.Close()
fstream.Dispose()
Dim filename As String = fileobj.Name
Dim bytesread As Integer = 0
Dim buffer As Integer = 8100
Dim fRequest As FtpWebRequest = WebRequest.Create(ftpPath & "/Logs/" & filename)
fRequest.Credentials = New NetworkCredential(username, psswd)
fRequest.KeepAlive = False
fRequest.Proxy = Nothing
fRequest.UsePassive = True
fRequest.UseBinary = False
fRequest.Method = WebRequestMethods.Ftp.UploadFile
fRequest.Timeout = 180000
Try
' read in file...
'Dim reader As New StreamReader(fileItem)
Dim fs As FileStream = File.OpenRead(fileItem)
Dim bFile As Byte() = New Byte(8100) {}
Dim fstream As Stream = fRequest.GetRequestStream
' upload file...
Do
bytesread = fs.Read(bFile, 0, buffer)
fs.Read(bFile, 0, buffer)
fstream.Write(bFile, 0, bFile.Length)
Loop Until bytesread = 0
fstream.Close()
fstream.Dispose()
Catch ex As Exception
appLogs.constructLog(ex.Message.ToString & " # ", True, True)
errorReporting(ex.Message.ToString & fileItem)
End Try
uploaded by writing in chunks.