ftp upload of multiple large files into one file - vb.net

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.

Related

Docusign download file from template which get illegal characters in file base64string format using Chilkat and rest api

I can get file from template which passing templateid and documentid, when retrun from api , i will get as base64string format, and when i try to convert as byte,
I get an error "Additional information: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters."
Here the code which i used to download file from template
Dim rest As New Chilkat.Rest
Dim success As Boolean
Dim bTls As Boolean = True
Dim port As Integer = 443
Dim bAutoReconnect As Boolean = True
success = rest.Connect("demo.docusign.net", port, bTls, bAutoReconnect)
If (success <> True) Then
Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
Debug.WriteLine(rest.LastErrorText)
Exit Sub
End If
rest.AddHeader("X-DocuSign-Authentication", "{ ""Username"": ""DocuSign#example.com"", ""Password"":""DocuSign_password"", ""IntegratorKey"":""DocuSign_Integrator_Key"" }")
Dim sbResponseBody As New Chilkat.StringBuilder
success = rest.FullRequestNoBodySb("GET", "/restapi/v2.1/accounts/xxxx/templates/xxxx-xxxx-xxxx-xxxx-xxxx/documents/x", sbResponseBody)
If (success <> True) Then
Debug.WriteLine(rest.LastErrorText)
Exit Sub
End If
Dim respStatusCode As Integer = rest.ResponseStatusCode
If (respStatusCode >= 400) Then
Debug.WriteLine("Response Status Code = " & respStatusCode)
Debug.WriteLine("Response Header:")
Debug.WriteLine(rest.ResponseHeader)
Debug.WriteLine("Response Body:")
Debug.WriteLine(sbResponseBody.GetAsString())
Exit Sub
End If
Dim jsonResponse As New Chilkat.JsonObject
jsonResponse.LoadSb(sbResponseBody)
Dim pdfBytes As Byte() = Convert.FromBase64String(sbResponseBody.ToString)
Regards,
Aravind
i changed my code from chilkat dll to Docusing dll 3.0.0 , using docusing dll i can download file from envelope, here i past my code , it will useful to some other developer.I am used .net framework code download file from file stream.
Private Function DoWnload(ByVal accessToken As String, ByVal basePath As String, ByVal accountId As String, ByVal envelopeId As String, ByVal documents As List(Of EnvelopeDocItem), ByVal docSelect As String) As String
Dim config = New Configuration(New ApiClient(basePath))
config.AddDefaultHeader("Authorization", "Bearer " & accessToken)
Dim envelopesApi As EnvelopesApi = New EnvelopesApi(config)
Dim results As System.IO.Stream = envelopesApi.GetDocument(accountId, envelopeId, docSelect)
Dim docItem As EnvelopeDocItem = documents.FirstOrDefault(Function(d) docSelect.Equals(d.DocumentId))
Dim docName As String = docItem.Name
Dim hasPDFsuffix As Boolean = docName.ToUpper().EndsWith(".PDF")
Dim pdfFile As Boolean = hasPDFsuffix
Dim docType As String = docItem.Type
If ("content".Equals(docType) OrElse "summary".Equals(docType)) AndAlso Not hasPDFsuffix Then
docName += ".pdf"
pdfFile = True
End If
If "zip".Equals(docType) Then
docName += ".zip"
End If
Dim mimetype As String
If pdfFile Then
mimetype = "application/pdf"
ElseIf "zip".Equals(docType) Then
mimetype = "application/zip"
Else
mimetype = "application/octet-stream"
End If
Dim bytesRead As Integer
Dim buffer(4096) As Byte
Using outFile As New System.IO.FileStream("C:\File.pdf", IO.FileMode.Create, IO.FileAccess.Write)
Do
bytesRead = results.Read(buffer, 0, buffer.Length)
If bytesRead > 0 Then
outFile.Write(buffer, 0, bytesRead)
End If
Loop While bytesRead > 0
End Using
Return ""
End Function
Dim envelopeDocItems As List(Of EnvelopeDocItem) = New List(Of EnvelopeDocItem) From {
New EnvelopeDocItem With {
.Name = "Combined",
.Type = "content",
.DocumentId = "combined"
},
New EnvelopeDocItem With {
.Name = "Zip archive",
.Type = "zip",
.DocumentId = "archive"
}
Thanks to Inbar Gazit...
Thanks and Regards,
Aravind
Here is an example: https://www.example-code.com/vbnet/docusign_download_envelope_document.asp
Also see the other VB.NET DocuSign examples: https://www.example-code.com/vbnet/docusign.asp

Google Drive Rest: convert does not work

I am using the G Drive REST endpoints (not .net client) to upload docx files through vb .net. My problem is that if even i declare the query parameter "convert" as true, the files are getting uploaded but they never auto-convert.
The first thing i do is to create a new file with POST and after that i upload the content with Put in the upload uri in a separate request.
it does not even work when i use the Google Playground to upload the docx files.
Public Shared Function UploadStream(fileStream As IO.Stream, filename As String, mimetype As String, target As String, accesstoken As String, Optional ConvertToGDoc As Boolean = False) As String
Try
Dim subject As String = ""
Dim doc As New Aspose.Words.Document
Dim docformat = Aspose.Words.FileFormatUtil.DetectFileFormat(fileStream) ' detect the format of the file Then 'check if the file is doc or docx
If docformat.LoadFormat = Aspose.Words.LoadFormat.Doc Or docformat.LoadFormat = Aspose.Words.LoadFormat.Docx Then 'check if the file is word document
doc = New Aspose.Words.Document(fileStream)
subject = doc.BuiltInDocumentProperties.Subject 'get the subject from the word file
If doc.BuiltInDocumentProperties.Subject = "" Then subject = "none"
Else
subject = "none" 'set the subject as none if the file is not word file
End If
Dim localmd5 = Files.MD5stream(fileStream)
Dim baseaddress = "https://www.googleapis.com/drive/v2/files?convert=" + ConvertToGDoc.ToString
Dim req = Net.HttpWebRequest.Create(baseaddress)
req.Method = "POST"
req.Headers.Add("Authorization", "Bearer " + System.Web.HttpUtility.UrlEncode(accesstoken))
req.ContentType = "application/json"
Dim writer = New Newtonsoft.Json.Linq.JTokenWriter()
writer.WriteStartObject()
writer.WritePropertyName("title")
writer.WriteValue(filename)
writer.WritePropertyName("parents")
writer.WriteStartArray()
writer.WriteRawValue("{'id':'" + target + "'}")
writer.WriteEndArray()
writer.WritePropertyName("properties")
writer.WriteStartArray()
writer.WriteRawValue("{'key':'Subject','value':'" + subject + "'},{'key':'MD5','value':'" + localmd5 + "'},{'key':'Author','value':''}")
writer.WriteEndArray()
writer.WriteEndObject()
Dim bodybytes = Text.Encoding.UTF8.GetBytes(writer.Token.ToString)
req.ContentLength = bodybytes.Length
Dim requestStream = req.GetRequestStream
requestStream.Write(bodybytes, 0, bodybytes.Length)
requestStream.Close()
Dim resp As System.Net.HttpWebResponse = req.GetResponse()
Dim response = New IO.StreamReader(resp.GetResponseStream, False).ReadToEnd
Dim json As Newtonsoft.Json.Linq.JObject
json = Newtonsoft.Json.Linq.JObject.Parse(response)
Dim fileId = json.SelectToken("id").ToString()
baseaddress = "https://www.googleapis.com/upload/drive/v2/files/" + fileId + "?uploadType=media&convert=" + ConvertToGDoc.ToString
req = Net.HttpWebRequest.Create(baseaddress)
req.Method = "Put"
req.Headers.Add("Authorization", "Bearer " + System.Web.HttpUtility.UrlEncode(accesstoken))
bodybytes = General.GetStreamAsByteArray(fileStream)
req.ContentLength = bodybytes.Length
req.ContentType = mimetype
requestStream = req.GetRequestStream
requestStream.Write(bodybytes, 0, bodybytes.Length)
requestStream.Close()
resp = req.GetResponse()
response = New IO.StreamReader(resp.GetResponseStream, False).ReadToEnd
Return fileId
Catch ex As Exception
Return Nothing
End Try
End Function
Shared Function GetStreamAsByteArray(ByVal stream As System.IO.Stream) As Byte()
Dim streamLength As Integer = Convert.ToInt32(stream.Length)
Dim fileData As Byte() = New Byte(streamLength) {}
stream.Position = 0
' Read the file into a byte array
stream.Read(fileData, 0, streamLength)
stream.Close()
ReDim Preserve fileData(fileData.Length - 2)
Return fileData
End Function
Public Shared Function MD5stream(ByVal File_stream As IO.Stream, Optional ByVal Seperator As String = Nothing) As String
Using MD5 As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim Hash() As Byte = MD5.ComputeHash(File_stream)
Return Replace(BitConverter.ToString(Hash), "-", Seperator)
End Using
End Function
Had anyone else the same problem?

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)

FTP upload ProgressBar in 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")

How to create directory on FTP server

I am using the following code for creating the folder on FTP server ; But its not working in my case :-
Dim sFilePath as string =filepath
Dim ftpResponse1 As FtpWebResponse
Dim ftpRequest1 As FtpWebRequest
Dim IsExists1 As Boolean = True
ftpRequest1 = CType(FtpWebRequest.Create(sFilePath), FtpWebRequest)
ftpRequest1.UseBinary = True
ftpRequest1.Credentials = New NetworkCredential(ZXFTPUSER, ZXFTPPASS)
ftpRequest1.UsePassive = True
ftpRequest1.Method = WebRequestMethods.Ftp.MakeDirectory
'ftpRequest1.KeepAlive = False
'ftpResponse1 = ftpRequest1.GetResponse()
'ftpResponse1 = ftpRequest1.GetResponse()
'Dim strstream1 As Stream = ftpResponse1.GetResponseStream()
'Dim strreader1 As New StreamReader(strstream1)
'Console.WriteLine(strreader1.ReadToEnd())
'strreader1.Close()
'strstream1.Close()
'ftpResponse1.Close()
Please help me.
In the above case i am not getting any error but when i am going to upload a rar file then it is giving the following exception
The remote server returned an error: (550) File unavailable (e.g., file not found, no access).
And File Upload code is given below
Public Sub FTPUpload(ByVal SourceFile() As IO.FileInfo, ByVal folderLevel As Integer, ByVal ftpPassiveMode As Boolean)
ZXFTPPASS = "******"
Dim filePath As New IO.DirectoryInfo(filePaths)
Dim ftpRequest As FtpWebRequest
Dim dResult As Windows.Forms.DialogResult
Dim ftpFilePath As String = ""
Dim levelPath As String = ""
Dim iLoop As Integer
Dim uFile As IO.FileInfo
For Each uFile In SourceFile
Try
ftpFilePath = levelPath & "/" & uFile.Name
ftpRequest = CType(FtpWebRequest.Create(ftpFilePath), FtpWebRequest)
ftpRequest.Credentials = New NetworkCredential(ZXFTPUSER, ZXFTPPASS)
ftpRequest.UsePassive = ftpPassiveMode
ftpRequest.UseBinary = True
ftpRequest.KeepAlive = False
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile
'Read in the file
Dim b_file() As Byte = System.IO.File.ReadAllBytes(filePath.FullName & "\" & uFile.Name.ToString())
'Upload the file
Dim cls_stream As Stream = ftpRequest.GetRequestStream()
cls_stream.Write(b_file, 0, b_file.Length)
cls_stream.Close()
cls_stream.Dispose()
'MsgBox("Uploaded Successfully", MsgBoxStyle.Information)
Catch
MsgBox("Failed to upload.Please check the ftp settings", MsgBoxStyle.Critical)
End Try
Next
End Sub
Looking through various sites I have found this:
Private Function FtpFolderCreate(folder_name As String, username As String, password As String) As Boolean
Dim request As Net.FtpWebRequest = CType(FtpWebRequest.Create(folder_name), FtpWebRequest)
request.Credentials = New NetworkCredential(username, password)
request.Method = WebRequestMethods.Ftp.MakeDirectory
Try
Using response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
' Folder created
End Using
Catch ex As WebException
Dim response As FtpWebResponse = DirectCast(ex.Response, FtpWebResponse)
' an error occurred
If response.StatusCode = FtpStatusCode.ActionNotTakenFileUnavailable Then
Return False
End If
End Try
Return True
End Function
this is working code on how to create a directory on a FTP server Via Vb.net
Dim folderName As String = "POP/" & Date.Now.Year.ToString & Date.Now.Month.ToString.PadLeft(2, "0"c) & Date.Now.Day.ToString.PadLeft(2, "0"c)
Dim RequestFolderCreate As Net.FtpWebRequest = CType(FtpWebRequest.Create("ftp://" & server & "/" & folderName), FtpWebRequest)
RequestFolderCreate.Credentials = New NetworkCredential(username, password)
RequestFolderCreate.Method = WebRequestMethods.Ftp.MakeDirectory
Try
Using response As FtpWebResponse = DirectCast(RequestFolderCreate.GetResponse(), FtpWebResponse)
End Using
Catch ex As Exception//catch a expection