when client is closed server crash - vb.net

I have a problem when I connect to the server from the client, it connects without any issues, but when I close the client window, the server shows the following error message:
The length can not be less than zero. Parameter name: length
And then when I try to reconnect the client it crashes too
This is the server source code:
serverSocket.Start()
AddInfo("Server Started", ConsoleColor.Cyan)
AddInfo("---------------- ACCOUNTS ----------------", ConsoleColor.Blue)
Dim AN As Integer = 0
For Each f In Directory.GetFiles("saved\accounts\")
Dim acc As String = Path.GetFileNameWithoutExtension(f).Split(CChar("%"))(0)
Dim pass As String = Path.GetFileNameWithoutExtension(f).Split(CChar("%"))(1)
AddInfo(acc & " - " & pass, ConsoleColor.Magenta)
AN += 1
Next
AddInfo(AN & " Accounts exists .", ConsoleColor.DarkCyan)
AddInfo("-----------------------------------------------", ConsoleColor.Blue)
clientSocket = serverSocket.AcceptTcpClient()
AddInfo("New Client Connected", ConsoleColor.Yellow)
clients_number += 1
AddInfo("Clients Num : " & clients_number, ConsoleColor.DarkYellow)
requestCount = 0
While (True)
'RECEIVING
requestCount = requestCount + 1
serverStream = clientSocket.GetStream()
Dim bytesFrom(10024) As Byte
serverStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
Dim dataFromClient As String = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
AddInfo("Data from client - " + dataFromClient, ConsoleColor.DarkYellow)
'### CHEKING ACCOUNT ###
For Each f In Directory.GetFiles("saved\accounts\")
If dataFromClient = Path.GetFileNameWithoutExtension(f) Then
account_avaible = True
End If
Next
If account_avaible = True Then
Dim serverResponse As String = ""
Dim l As New List(Of String)
l.AddRange(File.ReadAllLines("saved\accounts\" & dataFromClient & ".inf"))
For i = 0 To l.Count - 1
serverResponse += l.Item(i).ToString.Split(CChar("="))(1) & "|"
Next
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(serverResponse)
serverStream.Write(sendBytes, 0, sendBytes.Length)
serverStream.Flush()
AddInfo(serverResponse, ConsoleColor.Green)
Else
Dim serverResponse As String = "connection_false"
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(serverResponse)
serverStream.Write(sendBytes, 0, sendBytes.Length)
serverStream.Flush()
AddInfo(serverResponse, ConsoleColor.Green)
account_avaible = False
End If
End While

I've fixed this problem . thanks #WDS .
i deleted the loop and i made a return to the clientSocket = serverSocket.AcceptTcpClient()
this is the source :
`serverSocket.Start() : AddInfo("Server Started", ConsoleColor.Cyan)
AddInfo("---------------- ACCOUNTS ----------------", ConsoleColor.Blue)
Dim AN As Integer = 0
For Each f In Directory.GetFiles("saved\accounts\")
Dim acc As String = Path.GetFileNameWithoutExtension(f).Split(CChar("%"))(0)
Dim pass As String = Path.GetFileNameWithoutExtension(f).Split(CChar("%"))(1)
AddInfo(acc & " - " & pass, ConsoleColor.Magenta)
AN += 1
Next
AddInfo(AN & " Accounts exists .", ConsoleColor.DarkCyan)
AddInfo("-----------------------------------------------", ConsoleColor.Blue)
Dodo:
account_avaible = False
clientSocket = serverSocket.AcceptTcpClient()
AddInfo("New Client Connected", ConsoleColor.Yellow)
clients_number += 1
AddInfo("Clients Num : " & clients_number, ConsoleColor.DarkYellow)
requestCount = 0
'RECEIVING
requestCount = requestCount + 1
serverStream = clientSocket.GetStream()
Dim bytesFrom(10024) As Byte
serverStream.Read(bytesFrom, 0, clientSocket.ReceiveBufferSize)
Dim dataFromClient As String = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
AddInfo("Data from client - " + dataFromClient, ConsoleColor.DarkYellow)
'### CHEKING ACCOUNT ###
For Each f In Directory.GetFiles("saved\accounts\")
If dataFromClient = Path.GetFileNameWithoutExtension(f) Then
account_avaible = True
End If
Next
If account_avaible = True Then
Dim serverResponse As String = ""
Dim l As New List(Of String)
l.AddRange(File.ReadAllLines("saved\accounts\" & dataFromClient & ".inf"))
For i = 0 To l.Count - 1
serverResponse += l.Item(i).ToString.Split(CChar("="))(1) & "|"
Next
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(serverResponse)
serverStream.Write(sendBytes, 0, sendBytes.Length)
serverStream.Flush()
AddInfo(serverResponse, ConsoleColor.Green)
Else
Dim serverResponse As String = "connection_false"
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(serverResponse)
serverStream.Write(sendBytes, 0, sendBytes.Length)
serverStream.Flush()
AddInfo(serverResponse, ConsoleColor.Green)
account_avaible = False
End If
GoTo Dodo
'clientSocket.Close()
'serverSocket.Stop()`
But now i have new problem =/ when i enter an incorrect account msg show ("Incorrect account") and then when i try to enter an other account the client bugg (freeze)

Related

Socket abilities

I am making a board game for some users. I am learning how to send and receive messages from a socket server.
Private Sub doChat()
Dim requestCount As Integer
Dim bytesFrom(10024) As Byte
Dim dataFromClient As String
Dim sendBytes As [Byte]()
Dim serverResponse As String
Dim rCount As String
requestCount = 0
While (True)
Try
requestCount = requestCount + 1
Dim networkStream As NetworkStream = _
clientSocket.GetStream()
networkStream.Read(bytesFrom, 0, bytesFrom.Length)
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = _
dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
msg("From client-" + clNo + dataFromClient)
rCount = Convert.ToString(requestCount)
serverResponse = "Server to clinet(" + clNo + ") " + dataFromClient
sendBytes = Encoding.ASCII.GetBytes(serverResponse)
networkStream.Write(sendBytes, 0, sendBytes.Length)
networkStream.Flush()
msg(serverResponse)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End While
End Sub
My question is, what else can I send or receive by sockets? Can I send events? Functions? Elements? Structures? What is the method? I didn't find any article or video clip about this.

how to add filters on vb HttpWebRequest

This code, is working perfectly (getting data with web request) :
Protected Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim oauth_token = "8e269b44b2d7d73eb0b46112af5f4xxx"
Dim oauth_token_secret = "80da1edadcba1e66e47d2e20f075cxxx"
Dim oauth_consumer_key = "3626311748bcf2072da2bd475fccfxxx"
Dim oauth_consumer_secret = "0cbb0df8d840e22b96d4f80449e7exxx"
Dim oauth_version = "1.0"
Dim oauth_signature_method = "HMAC-SHA1"
Dim oauth_nonce = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
Dim timeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
Dim oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
Dim resource_url = "http://www.inart.com/api/rest/products/store/1"
Dim baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}"
Dim baseString = String.Format(baseFormat, oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_token, oauth_version)
baseString = String.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString))
Dim compositeKey = String.Concat(Uri.EscapeDataString(oauth_consumer_secret), "&", Uri.EscapeDataString(oauth_token_secret))
Dim oauth_signature As String
Using hasher As New HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey))
oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)))
End Using
Dim headerFormat = "OAuth oauth_nonce=""{0}"", oauth_signature_method=""{1}"", " + "oauth_timestamp=""{2}"", oauth_consumer_key=""{3}"",
" + "oauth_token=""{4}"", oauth_signature=""{5}"", " + "oauth_version=""{6}"""
Dim authHeader = String.Format(headerFormat, Uri.EscapeDataString(oauth_nonce), Uri.EscapeDataString(oauth_signature_method), Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_consumer_key), Uri.EscapeDataString(oauth_token), Uri.EscapeDataString(oauth_signature), Uri.EscapeDataString(oauth_version))
ServicePointManager.Expect100Continue = True
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(resource_url), HttpWebRequest)
request.Headers.Add("Authorization", authHeader)
request.Method = "GET"
request.ContentType = "application/json"
request.Accept = "application/json"
Try
Dim response As WebResponse = request.GetResponse()
Dim datastream As Stream = response.GetResponseStream
Dim reader As StreamReader = New StreamReader(datastream)
Dim responsefromserver As String = reader.ReadToEnd
If responsefromserver = Nothing Then
TextBox1.Text = "No response from server"
Else
Dim json As String = responsefromserver
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
Dim output As String = ""
Dim successReq As Boolean = False
Dim avDom As String = ""
Dim counter As Integer = 0
For Each item As JProperty In data
item.CreateReader()
output += "|-" & item.Name.ToString & " : " & item.Value.ToString & "-"
output += Environment.NewLine
counter += 1
Next
TextBox1.Text = output
TextBox1.Text += Environment.NewLine + counter.ToString
reader.Close()
response.Close()
End If
Catch ex As Exception
TextBox1.Text = ex.Message.ToString
End Try
End Sub
When i try to add some filters, it fails. for example, I try to add the limit filter this way : Dim resource_url = "http://www.inart.com/api/rest/products/store/1?limit=1".
I am sure that the filter is ok because i tried at postman application and it is working! see print screen
What should I change or add?
Thank you.
Dim url As String = "http://www.inart.com/api/rest/products/store/1?limit=1&page=2"
Dim oauthconsumerkey As String = "3626311748bcf2072da2bd475fccssss"
Dim oauthconsumersecret As String = "0cbb0df8d840e22b96d4f80449sssss"
Dim oauthtoken As String = "8e269b44b2d7d73essss2af5f454e"
Dim oauthtokensecret As String = "80da1edadcba1e66e47d2e2sssss"
Dim oauthsignaturemethod As String = "HMAC-SHA1"
Dim oauthversion As String = "1.0"
Dim oauthnonce As String = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
Dim timeSpan As TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
Dim oauthtimestamp As String = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
Dim basestringParameters As SortedDictionary(Of String, String) = New SortedDictionary(Of String, String)()
basestringParameters.Add("limit", "1")
basestringParameters.Add("page", "2")
basestringParameters.Add("oauth_version", oauthversion)
basestringParameters.Add("oauth_consumer_key", oauthconsumerkey)
basestringParameters.Add("oauth_nonce", oauthnonce)
basestringParameters.Add("oauth_signature_method", oauthsignaturemethod)
basestringParameters.Add("oauth_timestamp", oauthtimestamp)
basestringParameters.Add("oauth_token", oauthtoken)
Dim baseString As StringBuilder = New StringBuilder()
baseString.Append("GET" & "&")
baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split("?"c)(0)) & "&"))
For Each entry As KeyValuePair(Of String, String) In basestringParameters
baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key & "=" + entry.Value & "&")))
Next
Dim finalBaseString As String = baseString.ToString().Substring(0, baseString.Length - 3)
Dim signingKey As String = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) & "&" + EncodeCharacters(Uri.EscapeDataString(oauthtokensecret))
Dim hasher As HMACSHA1 = New HMACSHA1(New ASCIIEncoding().GetBytes(signingKey))
Dim oauthsignature As String = Convert.ToBase64String(hasher.ComputeHash(New ASCIIEncoding().GetBytes(finalBaseString)))
ServicePointManager.Expect100Continue = False
Dim wRequest As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
Dim authorizationHeaderParams As StringBuilder = New StringBuilder()
authorizationHeaderParams.Append("OAuth ")
authorizationHeaderParams.Append("oauth_nonce=" & """" + Uri.EscapeDataString(oauthnonce) & """,")
authorizationHeaderParams.Append("oauth_signature_method=" & """" + Uri.EscapeDataString(oauthsignaturemethod) & """,")
authorizationHeaderParams.Append("oauth_timestamp=" & """" + Uri.EscapeDataString(oauthtimestamp) & """,")
authorizationHeaderParams.Append("oauth_consumer_key=" & """" + Uri.EscapeDataString(oauthconsumerkey) & """,")
If Not String.IsNullOrEmpty(oauthtoken) Then authorizationHeaderParams.Append("oauth_token=" & """" + Uri.EscapeDataString(oauthtoken) & """,")
authorizationHeaderParams.Append("oauth_signature=" & """" + Uri.EscapeDataString(oauthsignature) & """,")
authorizationHeaderParams.Append("oauth_version=" & """" + Uri.EscapeDataString(oauthversion) & """")
wRequest.Headers.Add("Authorization", authorizationHeaderParams.ToString)
wRequest.Method = "GET"
wRequest.ContentType = "application/json"
wRequest.Accept = "application/json"
Try
Dim wResponse As WebResponse = wRequest.GetResponse()
Dim dataStream As Stream = wResponse.GetResponseStream()
Dim reader As StreamReader = New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
If responseFromServer = Nothing Then
TextBox1.Text = "No response from server"
Else
Dim json As String = responseFromServer
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
Dim output As String = ""
Dim successReq As Boolean = False
Dim avDom As String = ""
For Each item As JProperty In data
item.CreateReader()
output += "|-" & item.Name.ToString & " : " & item.Value.ToString & "-"
output += Environment.NewLine
Next
TextBox1.Text = output
End If
Catch ex As Exception
TextBox1.Text = ex.Message.ToString
End Try
Private Function EncodeCharacters(ByVal data As String) As String
If data.Contains("!") Then data = data.Replace("!", "%21")
If data.Contains("'") Then data = data.Replace("'", "%27")
If data.Contains("(") Then data = data.Replace("(", "%28")
If data.Contains(")") Then data = data.Replace(")", "%29")
If data.Contains("*") Then data = data.Replace("*", "%2A")
If data.Contains(",") Then data = data.Replace(",", "%2C")
Return data
End Function
This example is working

How to Calculate estimated time remaining in downloading Using Xceed.Ftp.FtpClient() in VB.net?

I am downloading FTP files using Xceed.Ftp.FtpClient() how can i calculated the estimated remaining Time?
Dim HostName As String = (New Uri(RemoteFilePath).Host).ToString()
Dim RemoteFolderName As String = System.IO.Path.GetFileName((New Uri(RemoteFilePath).LocalPath).ToString())
Dim RemoteFileName As String = System.IO.Path.GetFileName((New Uri(RemoteFilePath).LocalPath).ToString())
Dim LocalFileName As String = System.IO.Path.GetFileName((New Uri(LocalFilePath).LocalPath).ToString())
Dim Ftp As New Xceed.Ftp.FtpClient()
Dim AuthMethod As AuthenticationMethod = AuthenticationMethod.Tls
Dim VeriFlag As VerificationFlags = VerificationFlags.None
Dim Cert As Certificate = Nothing
Ftp.Connect(HostName, 990, AuthMethod, VeriFlag, Cert)
'Console.WriteLine("Connected")
Ftp.Login(username, pass)
Dim s As String = Ftp.GetCurrentFolder()
'Console.WriteLine("LogedIn")
Ftp.ChangeCurrentFolder("WindowsPatches/" & RemoteFolderName)
'Console.WriteLine("Remote Folder Name:" & RemoteFolderName)
'Ftp.ChangeCurrentFolder(RemoteFolderName)
Dim files = Ftp.GetFolderContents()
If files IsNot Nothing AndAlso files.Count >= 0 Then
For index = 0 To files.Count - 1
If files.Item(index).Type = FtpItemType.File Then
RemoteFileName = files.Item(index).Name
LocalFileName = RemoteFileName
If Not Directory.Exists(RemoteFolderName) Then
Directory.CreateDirectory(RemoteFolderName)
End If
LocalFileName = RemoteFolderName & "\" & LocalFileName
If Not String.IsNullOrEmpty(LocalFilePath) AndAlso System.IO.File.Exists(LocalFilePath) Then
System.IO.File.Delete(LocalFilePath)
End If
'Console.WriteLine("Downloading started...")
Ftp.ReceiveFile(RemoteFileName, LocalFileName)
'Console.WriteLine("Downloading Complete")
'Console.WriteLine("Working Path" & Directory.GetCurrentDirectory())
Dim psi As New ProcessStartInfo()
Directory.SetCurrentDirectory(LocalFilePath & RemoteFolderName)
'Console.WriteLine("Local Directory Name: " & LocalFilePath & RemoteFolderName)
psi.CreateNoWindow = True
psi.FileName = RemoteFileName
psi.UseShellExecute = True
Dim myProcess As Process = Process.Start(psi)
Console.WriteLine("Update process started...")
'Exit For
End If
Next
'LocalFileName = RemoteFileName
End If
I am using this code, any suggestion please?

how to use componentone c1printdocument in asp.net for reading text file and convert into pdf with format?

I am using the C1PrintDocument class to read a text file and convert into pdf in web. Actually it converts into pdf but without the format as like in text file.
For eg. I have a text file which has only one page. But it makes into two pages while convert into pdf. Below is the code what I use.
Imports System.IO
Imports C1.C1Preview
Imports C1.C1Pdf
Imports C1.Web.Wijmo.Controls.C1ReportViewer
Imports System.Runtime.Serialization.Formatters.Binary
Imports C1.C1Pdf.PdfDocumentInfo
Imports C1.C1Preview.C1PrintDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
Try
Dim strmappath As String = System.Web.HttpContext.Current.Server.MapPath("~")
Dim filename As String
filename = Path.Combine(Server.MapPath("~"), "12214.txt")
Dim sr As New System.IO.StreamReader(filename, System.Text.Encoding.UTF8)
Dim str As [String] = sr.ReadToEnd()
Dim doc1 As C1PrintDocument = C1ReportViewer.CreateC1PrintDocument()
Dim doc As New C1PrintDocument
doc.Pages(1).PageSettings.TopMargin = 0
doc.Pages(1).PageSettings.LeftMargin = 0
doc.Pages(1).PageSettings.RightMargin = 0
doc.StartDoc()
Dim overlay As New RenderArea()
overlay.Width = "100%"
overlay.Height = "100%"
overlay.Style.Borders.All = LineDef.Default
doc.PageLayout.Overlay = overlay
Dim lines As String() = System.IO.File.ReadAllLines(filename)
Dim linecnt As Integer = System.IO.File.ReadLines(filename).Count
Dim strpages1 As String()
ReDim strpages1(Math.Abs(linecnt / 66) - 1)
Dim intcnt As Integer
Dim intlinereadcnt As Integer
intlinereadcnt = 0
intcnt = 0
intlinereadcnt = 0
For Each line In lines
If intcnt <= 66 Then
If intcnt <> 66 Then
strpages1(intlinereadcnt) = strpages1(intlinereadcnt) &
line & vbCrLf
End If
intcnt = intcnt + 1
ElseIf intcnt = 67 Then
intlinereadcnt = intlinereadcnt + 1
intcnt = 0
End If
Next
Dim strPages As String() = str.Split(Chr(12))
Dim strPage As String = String.Empty
Dim txtPage As New C1.C1Preview.RenderText(doc)
With doc
.AllowNonReflowableDocs = True
For Each strPage In strpages1
If strPage.Length > 0 Then
txtPage.Text = strPage
txtPage.X = 150
doc.Style.TextColor = Drawing.Color.Blue
.RenderBlockText(txtPage.Text)
.Style.WordWrapMode = False
.NewPage()
End If
Next
End With
Dim m_pdfExporter As C1.C1Preview.Export.PdfExporter
m_pdfExporter = C1.C1Preview.Export.ExportProviders.
PdfExportProvider.NewExporter()
m_pdfExporter.Document = doc
m_pdfExporter.Export(Server.MapPath("~") & "12214" & ".pdf")
Dim sr2 As System.IO.MemoryStream
sr2 = New MemoryStream
doc.Save(sr2)
Dim biteArray As Byte() = New Byte(sr2.Length - 1) {}
sr2.Position = 0
sr2.Read(biteArray, 0, CInt(sr2.Length))
'm_pdfExporter.Export(Path.GetTempPath & "\" & "12214" & ".pdf")
Response.Clear()
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/pdf"
'Response.BinaryWrite(biteArray)
Response.AddHeader("Content-Disposition", "attachment;filename=" & "12214" & ".pdf")
Response.BinaryWrite(System.IO.File.ReadAllBytes(Server.MapPath("~") & "12214" & ".pdf"))
Catch ex As Exception
End Try
End Sub
Try using c1PrintDocument1.Export("filename.pdf", true) instead.
Thanks,
Richa

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.