Creating a file on my website using VB.net - vb.net

I have searched but couldn't get any real solution to creating a file on my website by uploading the file from the local system using VB.net
This is my code so far
Dim rdr As New FileStream(ReSaveFile, FileMode.Open)
Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://www.timemedian.com/display.txt"), HttpWebRequest)
req.Method = "POST"
' you might use "POST"
req.ContentLength = rdr.Length
req.AllowWriteStreamBuffering = True
Dim reqStream As Stream = req.GetRequestStream()
Dim inData As Byte() = New Byte(rdr.Length - 1) {}
' Get data from upload file to inData
Dim bytesRead As Integer = rdr.Read(inData, 0, rdr.Length)
' put data into request stream
reqStream.Write(inData, 0, rdr.Length)
rdr.Close()
req.GetResponse()
' after uploading close stream
reqStream.Close()
but I cant possible see the error. Please help

I uploaded the file using ftp protocol like this
Try
Dim mReq1 As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://ftp.websitename.com//" & SetID & ".pvx"), System.Net.FtpWebRequest)
mReq1.Credentials = New System.Net.NetworkCredential("username", "password")
mReq1.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim MFile1() As Byte = System.IO.File.ReadAllBytes(ReSaveFile)
Dim mStream1 As System.IO.Stream = mReq1.GetRequestStream()
mStream1.Write(MFile1, 0, MFile1.Length)
mStream1.Close()
mStream1.Dispose()
Catch ex As Exception
MsgBox("Your file was not fully posted to the remote server. PVX Mail may not function properly")
Exit Sub
End Try

Related

VB.NET File upload using WebApi: UnExpected end of MIME

Everything seems to be working except I get this below error in the WEBAPI:
Unexpected end of MIME multipart stream. MIME multipart message is not complete.
When I upload the same file from postman to the WEBAPI endpoint it works perfectly. Makes me think its a problem with the VB application.
BTW: Not skilled in VB (Inherited Application trying to make it work to upload large files)
Dim fileBytes As Byte() = Nothing
Dim boundary As String = "---------------------------" + DateTime.Now.Ticks.ToString("x")
Using binaryReader As New BinaryReader(fileUpload1.PostedFile.InputStream)
fileBytes = binaryReader.ReadBytes(binaryReader.BaseStream.Length)
binaryReader.Close()
End Using
Dim request As HttpWebRequest =
WebRequest.Create("http://mylocalhost/api/directory")
request.Method = "POST"
request.ContentType = "multipart/form-data; boundary = " + boundary
request.ContentLength = fileBytes.Length
request.Accept = "*/*"
request.AutomaticDecompression = DecompressionMethods.GZip
request.KeepAlive = True
Dim newStream As IO.Stream = request.GetRequestStream()
newStream.Write(fileBytes, 0, fileBytes.Length)
'newStream.Close()
Dim response As WebResponse = request.GetResponse()
' Display the status.
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
' Get the stream containing content returned by the server.
Dim dataStream As IO.Stream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
Debug.WriteLine("File uploaded")
Return True````

Edit text file on server using VB

I would like to edit a text file on a server I have and I'm not really sure to begin. What I'm looking for is something like this:
dim username as string
dim password as string
dim serveraddr as string
username = "MyUsername"
password = "MyPassword"
serveraddr = "MyServer.hosting.com"
ConnectToServer(serveraddr, username, password)
WriteToFile("sample.txt", "Hello World")
Something like this. Obviously I just made the last two "methods" up so I guess those are what I am looking for except I don't know what they are called.
The Best Way Would Be To Delete The File From The Server And Rewriting It From Your App , Else If You Want To Add Info To The File You Can Download It To The Local Machine Then Add The Info , Delete It From The Server And Re-uploading it
Function For Deleting it
Private Function deletefile(ByRef filepathinftp As String, ByRef password As String, ByRef username As String)
Dim ftp As FtpWebRequest = DirectCast(WebRequest.Create(filepathinftp), FtpWebRequest)
Try
ftp.Credentials = New System.Net.NetworkCredential(username, password)
ftp.Method = WebRequestMethods.Ftp.DeleteFile
Dim ftpResponse As FtpWebResponse = CType(ftp.GetResponse(), FtpWebResponse)
ftpResponse = ftp.GetResponse()
ftpResponse.Close()
Catch ex As Exception
End Try
End Function
Function For Downloading From An Ftp
Dim request As FtpWebRequest = DirectCast(WebRequest.Create("File Path In Ftp Example: ftp ://mysite.com/file.txt"), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.DownloadFile
' This example assumes the FTP site uses anonymous logon.
request.Credentials = New NetworkCredential("username", "password")
Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
Dim responseStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(responseStream)
Dim text As String = reader.ReadToEnd
Finally here is the function for uploading
Public Sub UploadFile(ByVal _FileName As String, ByVal _UploadPath As String, ByVal _FTPUser As String, ByVal _FTPPass As String)
Dim _FileInfo As New System.IO.FileInfo(_FileName)
' Create FtpWebRequest object from the Uri provided
Dim _FtpWebRequest As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(New Uri(_UploadPath)), System.Net.FtpWebRequest)
' Provide the WebPermission Credintials
_FtpWebRequest.Credentials = New System.Net.NetworkCredential(_FTPUser, _FTPPass)
' By default KeepAlive is true, where the control connection is not closed
' after a command is executed.
_FtpWebRequest.KeepAlive = False
' set timeout for 20 seconds
_FtpWebRequest.Timeout = 20000
' Specify the command to be executed.
_FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
' Specify the data transfer type.
_FtpWebRequest.UseBinary = True
' Notify the server about the size of the uploaded file
_FtpWebRequest.ContentLength = _FileInfo.Length
' The buffer size is set to 2kb
Dim buffLength As Integer = 2048
Dim buff(buffLength - 1) As Byte
' Opens a file stream (System.IO.FileStream) to read the file to be uploaded
Dim _FileStream As System.IO.FileStream = _FileInfo.OpenRead()
Try
' Stream to which the file to be upload is written
Dim _Stream As System.IO.Stream = _FtpWebRequest.GetRequestStream()
' Read from the file stream 2kb at a time
Dim contentLen As Integer = _FileStream.Read(buff, 0, buffLength)
' Till Stream content ends
Do While contentLen <> 0
' Write Content from the file stream to the FTP Upload Stream
_Stream.Write(buff, 0, contentLen)
contentLen = _FileStream.Read(buff, 0, buffLength)
Loop
' Close the file stream and the Request Stream
_Stream.Close()
_Stream.Dispose()
_FileStream.Close()
_FileStream.Dispose()
Catch ex As Exception
MessageBox.Show(ex.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub

VB.NET Show message after FTP upload complete

I'm trying to create a uploader to FTP, although the file uploads perfectly, I am just wondering how I would be able to show a message after the ftp process has complete.
Close()
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim r As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 8
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
Next
Using ms As New System.IO.MemoryStream
sc.CaptureDeskTopRectangle(Me.boundsRect).Save(ms, System.Drawing.Imaging.ImageFormat.Png)
Using wc As New System.Net.WebClient
wc.UploadData("ftp://MYUSERNAME:MYPASSWORD#MYSITE.COM/" + sb.ToString() + ".png", ms.ToArray())
End Using
End Using
How would I manage this?
Edit: Also as you can see I use a random string.. although If I use sb.ToString() twice will it give me the exact same result for both? If not how can I manage this??
You need to declare the Random as Static. The UploadData has a UploadDataCompleted event you can listen for.
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Static r As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 8
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
Next
Using ms As New System.IO.MemoryStream
sc.CaptureDeskTopRectangle(Me.boundsRect).Save(ms, System.Drawing.Imaging.ImageFormat.Png)
Using wc As New System.Net.WebClient
AddHandler wc.UploadDataCompleted, AddressOf UploadCompleted
wc.UploadData("ftp://MYUSERNAME:MYPASSWORD#MYSITE.COM/" + sb.ToString() + ".png", ms.ToArray())
End Using
End Using
Private Sub UploadCompleted(sender As Object, e As Net.UploadDataCompletedEventArgs)
'do completed work here
End Sub
I don't think you can use the UploadData like that. Here is a Link for an example of ftp uploading.
Public Shared Sub Main()
' Get the object used to communicate with the server.
Dim request As FtpWebRequest = DirectCast(WebRequest.Create("ftp://www.contoso.com/test.htm"), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.UploadFile
' This example assumes the FTP site uses anonymous logon.
request.Credentials = New NetworkCredential("anonymous", "janeDoe#contoso.com")
' Copy the contents of the file to the request stream.
Dim sourceStream As New StreamReader("testfile.txt")
Dim fileContents As Byte() = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd())
sourceStream.Close()
request.ContentLength = fileContents.Length
Dim requestStream As Stream = request.GetRequestStream()
requestStream.Write(fileContents, 0, fileContents.Length)
requestStream.Close()
Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription)
response.Close()
End Sub

Save MP3 file from URL in VB.NET

I'm attempting to download an .mp3 file from my server, and save it locally, in VB.NET. However, when I do so, the saved file is corrupt, as the contents contain multiple lines of things like below, with a ton of random/weird characters below them (I'm assuming the building blocks of the audio file).
Here's what I am seeing: http://i.troll.ws/11d37d00.png
date = "20130811_18:22:58.466";
host = "DC3APS421";
kbps = "48";
khz = "22050";
When I attempt to play the .mp3 file in WMP, it also says it's corrupt. This is the code I'm using to download and save it.
' Download the MP3 file contents
Dim request As WebRequest = WebRequest.Create("http://www.mysite.org/secure/speech/?text=Test.")
request.Credentials = CredentialCache.DefaultCredentials
Dim response As WebResponse = request.GetResponse()
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
response.Close()
Debug.Print("Downloaded. Saving to local Audio Cache...")
' Check and create the audio-cache directory
If (Not System.IO.Directory.Exists(WorkingDir + "\audio-cache\")) Then
Debug.Print("Audio cache directory doesn't exist. Creating... ")
System.IO.Directory.CreateDirectory(WorkingDir + "\audio-cache\")
Debug.Print("Created at " + WorkingDir + "\audio-cache\")
End If
Dim Data As String = responseFromServer
' Save the mp3 file!
Dim fileLoc As String = WorkingDir + "\audio-cache\" + Mp3Hash + ".mp3"
Dim fs As FileStream = Nothing
If (Not File.Exists(fileLoc)) Then
fs = File.Create(fileLoc)
Using fs
End Using
End If
If File.Exists(fileLoc) Then
Using sw As StreamWriter = New StreamWriter(fileLoc)
sw.Write(Data)
End Using
End If
Debug.Print("Saved successfully to " + fileLoc)
How can I properly download, and locally save, an mp3 file from a URL?
try this
Dim HttpReq As HttpWebRequest = DirectCast(WebRequest.Create("http://...."), HttpWebRequest)
Using HttpResponse As HttpWebResponse = DirectCast(HttpReq.GetResponse(), HttpWebResponse)
Using Reader As New BinaryReader(HttpResponse.GetResponseStream())
Dim RdByte As Byte() = Reader.ReadBytes(1 * 1024 * 1024 * 10)
Using FStream As New FileStream("FileName.extension", FileMode.Create)
FStream.Write(RdByte, 0, RdByte.Length)
End Using
End Using
End Using

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.