Writing FileStream to Local Path and not the server - vb.net

I have the following code working successfully:
Protected Sub ExportExcel_Click(sender As Object, e As EventArgs) Handles ExportExcel.Click
Dim warnings As Warning()
Dim streamids As String()
Dim mimeType As String
Dim encoding As String
Dim filenameExtension As String
Dim fileName As String = "D:\Report" & DateTime.Now.ToString("yyyyMMdd_HHmmss") & ".xls"
Dim bytes As Byte() = ReportViewer1.LocalReport.Render("Excel", Nothing, mimeType, encoding, filenameExtension, streamids, warnings)
Using fs As New FileStream(fileName, FileMode.Create)
fs.Write(bytes, 0, bytes.Length)
End Using
lblMessage.Text = Functions.GetMessageConfirm("Report downloaded successfully in your D:/ at: " & Now.ToString)
End Sub
This code saves the file in the web server. I want to save the file on the client machine.

You're halfway there, probably. You can't just save files on the client anyway. Clients are webbrowsers, and they run JavaScript.
What you can do is use the download functionality of webbrowsers, to let them download the file which you just created. To do so, put the output on the server in a directory from where it can be downloaded, then return the new URL to the client.

Related

VB.NET - Checking and Executing Updates?

So I have a very small bit of VB.NET that can check fine if theres an Update.
But theres a few issues:
It does this all while not stopping the main code from executing;
It wont even download the file;
I cant get it to close the app that found the Update/Downloaded the Update and then Open the new file.
How can I get it to do all of that?
Current Code:
Public Sub CheckForUpdates()
'Connect to the Version File and Open It/Read It's Contents;
Dim request As HttpWebRequest = WebRequest.Create("https://dl.dropboxusercontent.com/s/rrk7yhfjvy500jl/version.txt")
Dim response As HttpWebResponse = request.GetResponse()
Dim sr As StreamReader = New StreamReader(response.GetResponseStream())
'Set the Variables to the Appropriate Versions;
Dim newestversion As String = sr.ReadToEnd()
Dim currentversion As String = Application.ProductVersion
'If the program isn't up to date;
If Not newestversion.Contains(currentversion) Then
MessageBox.Show("Downloading update!")
'Download the Update;
Using wc = New WebClient()
'Download the newest EXE file and store it in the same Directory as the Current EXE file;
wc.DownloadFile("https://dl.dropboxusercontent.com/s/da3in67jjayvqsz/PRAGMA1.exe", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), "PRAGMA1.exe"))
End Using
End If
End Sub
(It doesnt work)

How do i decompress a String with GZip?

The compression works just fine, and decompression also, but what should i do if the application got closed directly after the String got compressed? How can i decompress it having the String only?
//Compress
Dim mem As New IO.MemoryStream
Dim gz As New System.IO.Compression.GZipStream(mem, IO.Compression.CompressionMode.Compress)
Dim sw As New IO.StreamWriter(gz)
sw.WriteLine("hello compression")
sw.Close()
Dim compressed As String = Convert.ToBase64String(mem.ToArray())
//Decompress
Dim mem2 As New IO.MemoryStream(mem.ToArray)
gz = New System.IO.Compression.GZipStream(mem2, IO.Compression.CompressionMode.Decompress)
Dim sr As New IO.StreamReader(gz)
MsgBox(sr.ReadLine)
sr.Close()
Dim decompressed As String = sr.ReadLine()
When the program is closed, the data in your memory stream is lost and not recoverable. You'll need to save the data to a file first.

How can I make this recursive function more efficient?

I created this function to recursively copy an entire directory from an FTP server. It works just fine except that it is about 4 times slower than using FileZilla to do the same operation. It takes approximately 55 seconds to download the directory in FileZilla but it takes 229 seconds with this function. What can I do to make it download/run faster?
Private Sub CopyEntireDirectory(ByVal directory As String)
Dim localPath = localDirectory & formatPath(directory)
'creates directory in destination path
IO.Directory.CreateDirectory(localPath)
'Gets the directory details so I can separate folders from files
Dim fileList As ArrayList = Ftp.ListDirectoryDetails(directory, "")
For Each item In fileList
'checks if it's a folder or file: d=folder
If (item.ToString().StartsWith("d")) Then
'gets the directory from the details
Dim subDirectory As String = item.ToString().Substring(item.ToString().LastIndexOf(" ") + 1)
CopyEntireDirectory(directory & "/" & subDirectory)
Else
Dim remoteFilePath As String = directory & "/" & item.ToString().Substring(item.ToString().LastIndexOf(" ") + 1)
Dim destinationPath = localPath & "\" & item.ToString().Substring(item.ToString().LastIndexOf(" ") + 1)
'downloads file to destination directory
Ftp.DownLoadFile(remoteFilePath, destinationPath)
End If
Next
End Sub
Below is the download function that is taking up all the time.
Public Sub DownLoadFile(ByVal fromFilename As String, ByVal toFilename As String)
Dim files As ArrayList = Me.ListDirectory(fromFilename, "")
Dim request As FtpWebRequest = Me.CreateRequestObject(fromFilename)
request.Method = WebRequestMethods.Ftp.DownloadFile
Dim response As FtpWebResponse = CType(request.GetResponse(), FtpWebResponse)
If response.StatusCode <> FtpStatusCode.OpeningData AndAlso response.StatusCode <> FtpStatusCode.DataAlreadyOpen Then
Throw New ApplicationException(Me.BuildCustomFtpErrorMessage(request, response))
End If
Dim fromFilenameStream As Stream = response.GetResponseStream()
Dim toFilenameStream As FileStream = File.Create(toFilename)
Dim buffer(BLOCK_SIZE) As Byte
Dim bytesRead As Integer = fromFilenameStream.Read(buffer, 0, buffer.Length)
Do While bytesRead > 0
toFilenameStream.Write(buffer, 0, bytesRead)
Array.Clear(buffer, 0, buffer.Length)
bytesRead = fromFilenameStream.Read(buffer, 0, buffer.Length)
Loop
response.Close()
fromFilenameStream.Close()
toFilenameStream.Close()
End Sub
The slowness would obviously be within then FTP commands. Running your other code recursively would likely be able to run a million times per second because there is nothing to it.
The FTP download (whatever it is) should have the ability to define the size of the chunks is grabs. This will be key in your speed. It needs to be optimized based on your connection speed and file size. There is no RIGHT number for everyone.
EDIT
Based on the new code, the issue is in your BLOCK_SIZE which I assume is a constant. Play with the size of this to get your optimal speed.
HINT: This should be a multiple of 1024

vb.net downloading file using WebClient always corrupted file

I'm trying to download a ZIP file from Dropbox but every time I try it stops and only downloads ~100 kb of the file. It seems to corrupt any file I download from it, but however if I try to download using a normal browser it works.
Dim remoteUri As String = "https://www.dropbox.com/-/-------/test.zip?dl=0"
Dim fileName As String = "test.zip"
Dim myStringWebResource As String = Nothing
Dim myWebClient As New WebClient()
myStringWebResource = remoteUri + fileName
myWebClient.DownloadFile(myStringWebResource, fileName)
Your remoteUri is wrong. You're adding the filename twice. That gives you a bad url.
Dim remoteUri As String = "https://www.dropbox.com/-/-------/{0}?dl=1"
Dim fileName As String = "test.zip"
Dim myStringWebResource As String = Nothing
Dim myWebClient As New WebClient()
myStringWebResource = String.Format(remoteUri, fileName)
myWebClient.DownloadFile(myStringWebResource, fileName)
Try adding dl=1 to force download.

How to Upload Last Modified File **with the Name of the File** with FTP - VB - Still Missing Code-

There has been an EDIT to this title 1:17:45 AM EST 12/29/13
Good Morning,
I'm currently working on a solution to have a program upload the most recently modified file in a specific directory to an online storage site, but I'm running into an issue specifying the most recently modified file in the directory.
I'm by no means a programmer, but I have recently been inspired to learn VB Script. All related articles I have reviewed include additional processes, but I can not seem to chop up the codes to use them successfully so I am hoping that someone could help me.
EDIT* There is no error message but I simply just do not know how to tell the program to upload the most recently modified file.
This is my first time posting on this site and the community here is great! Below is the code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("FTP://ftp.DRIVEHQ.COM/information.zip"), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("username", "password")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte = System.IO.File.ReadAllBytes("C:\Users\Public\Documents\LAST MODIFIED FILE")
Dim Strz As System.IO.Stream = request.GetRequestStream()
Strz.Write(file, 0, file.Length)
Strz.Close()
Strz.Dispose()
Also the extension of the file I am looking for will be a .zip. Any contributions are greatly appreciated!
I recently learned File navigation on a project that sends modified files to Azure.
Try this:
Imports System.IO
Dim Folder As String = "C:\User\Public\Documents\"
Dim Files() As String
'Find all zip files in folder
Files = Directory.GetFiles(Folder, "*.zip", SearchOption.AllDirectories)
Dim fi As FileInfo
Dim FileToUpload As String = ""
Dim LastModifiedTime As DateTime = "1/1/1700"
For Each sFile In Files
fi = New FileInfo(sFile)
'Find the last mofified zip file
If fi.LastWriteTimeUTC > LastModifiedTime Then
LastModifiedTime = fi.LastWriteTimeUTC
FileToUpload = sFile
End If
Next
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("FTP://ftp.DRIVEHQ.COM/" & fi.Name), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("username", "password")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte = System.IO.File.ReadAllBytes(FileToUpload)
Dim Strz As System.IO.Stream = request.GetRequestStream()
Strz.Write(file, 0, file.Length)
Strz.Close()
Strz.Dispose()