Cannot download zip file in FireFox - vb.net

I am using the zip component to create a zip from memory and stream that file to download. It was working for a while, but in FireFox it won't let me download the file. Here is the code that I am using:
' NewZip initializes the zip object. It does not write
' the file. The "test.zip" file, in this case, will never be written.
success = zip.NewZip("lib-files.zip")
If (success <> True) Then
'MsgBox(zip.LastErrorText)
Exit Sub
End If
For Each oRow As Data.DataRow In oData.Tables(0).Rows
If System.IO.File.Exists(Application("LibUploadedDocumentPath") & oRow("DocFileName").ToString) = True Then
success = zip.AppendOneFileOrDir(Application("LibUploadedDocumentPath") & oRow("DocFileName").ToString, False)
Dim entry As Chilkat.ZipEntry
Dim fFile As FileInfo = New FileInfo(Application("LibUploadedDocumentPath") & oRow("DocFileName").ToString)
Dim sNewFileName As String = oRow("DocName").ToString
entry = zip.GetEntryByName(oRow("DocFileName").ToString)
If (entry Is Nothing) Then
MsgBox("Failed to find entry in .zip")
Exit Sub
End If
'Dim sTestName As String = ""
entry.FileName = sNewFileName & fFile.Extension.ToLower
Else
Response.Write("All the files are not found. Download aborted.")
Exit Sub
End If
Next
If (success <> True) Then
'MsgBox(zip.LastErrorText)
Exit Sub
End If
Dim Data As Byte()
Data = zip.WriteToMemory
Response.Clear()
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Length", Data.Length.ToString())
Response.AddHeader("Content-Disposition",
"attachment; filename=""" & zip.FileName & """")
Response.BinaryWrite(Data)
Response.Flush()
Response.End()
In FireFox it says, "the source file cannot be saved, because the source file could not be read". I've tried it in Chrome, and it allows me to download there. Not sure if its the component that's being used, or something else I need to add. Any thoughts?

Maybe change the content type to "application/zip"?
Response.ContentType = "application/zip"

Related

Show a popup after exporting in Excel in vb.net

Hi I've a procedure in my web site for exporting a datatable in xlsx with closedxml library and I want show a popup after finishing export but the popup not showed. Can anyone tell me how to show the popup ? This is my code
Protected Sub ExportExcel(dt, strTable)
Using wb As New XLWorkbook()
Dim ws = wb.Worksheets.Add(dt, "foglio1")
ws.Columns("I").Style.NumberFormat.Format = "#,##0.00"
Response.Clear()
Response.Buffer = True
Response.Charset = "UTF-8"
Response.ContentEncoding = System.Text.Encoding.Unicode
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment;filename=" & strTable & ".xlsx" )
try
Using MyMemoryStream As New MemoryStream()
wb.SaveAs(MyMemoryStream)
MyMemoryStream.WriteTo(Response.OutputStream)
Response.Flush()
Response.Close()
End Using
catch
finally
Dim scriptString as String = "<script language=JavaScript>"
scriptString += "alert('Export completed !" & strUser & "!');"
scriptString += "window.location.href='http://localhost/default.aspx';<"
scriptString += "/"
scriptString += "script>"
If(Not ClientScript.IsClientScriptBlockRegistered(Me.GetType(), "clientScript"))
ClientScript.RegisterClientScriptBlock(Me.GetType(), "clientScript",scriptString)
end If
end try
End Using
End Sub

Google Drive API v3 VB.NET Upload To Spesific Folder

Please Help, i'm trying to upload file to specific folder in my google drive using Vb.net. but, i'm googling for hours and not get working code. i cant sleep because this. here is my code:
Private Sub UploadFile(FilePath As String)
Try
If Service.ApplicationName <> "Google Drive VB Dot Net" Then CreateService()
Dim TheFile As New File()
TheFile.Name = "Database Sekretariat.accdb"
TheFile.Description = "A test document"
'TheFile.MimeType = "text/plain"
TheFile.Parents(0) = "1uMeTMRtvhm5_98udPmV8kp19aGtrmeQj"
Dim ByteArray As Byte() = System.IO.File.ReadAllBytes(FilePath)
Dim Stream As New System.IO.MemoryStream(ByteArray)
Dim UploadRequest As FilesResource.CreateMediaUpload = Service.Files.Create(TheFile, Stream, TheFile.MimeType)
UploadRequest.Upload()
Dim file As File = UploadRequest.ResponseBody
MsgBox("Upload Selesai " & file.Name & "")
Catch ex As Exception
MsgBox("Upload Gagal")
End Try
End Sub
use it in the following way, it is functional
First, i look for the ID folder
Public Sub SearchFolder()
IDFolderSave = String.Empty 'Global Variable
Try
Dim findrequest As FilesResource.ListRequest = Service.Files.List
Dim listFolder As Data.FileList = findrequest.Execute
For Each item As File In listFolder.Files
If item.MimeType = "application/vnd.google-apps.folder" Then
If item.Name = "NameFolder" Then
IDFolderSave = item.Id.ToString
Exit For
End If
End If
Next
Catch ex As Exception
Throw ex
End Try
'MsgBox("Folder id: " + idFolder)
End Sub
Second, upload file
Public Sub UploadFileInFolder()
Dim FilePath As String = String.Empty
FilePath = "C:\Icons\Loadding.gif"
Dim plist As List(Of String) = New List(Of String)
SearchFolder()
plist.Add(IDFolderSave) 'Set parent folder
If (System.IO.File.Exists(FilePath)) Then
Dim fileMetadata = New File() With {
.Name = "Test",
.Parents = plist
}
Dim request As FilesResource.CreateMediaUpload
Using stream = New System.IO.FileStream(FilePath, System.IO.FileMode.Open)
request = Service.Files.Create(fileMetadata, stream, "application/octet-stream")
request.Fields = "id, parents"
request.Upload()
End Using
Dim file As File = request.ResponseBody
IDFileShared = file.Id
SharedFile()
MsgBox("File upload: " + file.Id)
Else
MsgBox("File does not exist: " + FilePath)
End If
End Sub
I hope it helps you

Exclude folder from being copied

Hi I know how to copy files from one folder to the next, but I've run into a snag when we need to exclude a folder. More specifically the ".svn" folder. I've tried using Not SourceDir.Name = skipDir but that doesn't seem to make a difference.
This is my code. Thank you for the help.
Private Sub CopyDirectoryContents(sourcePath As String, destinationPath As String)
Dim SourceDir As DirectoryInfo = New DirectoryInfo(sourcePath)
Dim DestDir As DirectoryInfo = New DirectoryInfo(destinationPath)
Dim skipDir As String = ".svn"
Cursor = Cursors.WaitCursor
Try
If Not Directory.Exists(sourcePath) Then
MsgBox("The directory path entered does not exist. Please re-enter your source directory path", MsgBoxStyle.Exclamation, Title:="Missing source directory")
Return
txtSubfolder.Focus()
End If
If Not Directory.Exists(destinationPath) Then
MsgBox("The destination directory does not exist. Creating folder for it.", MsgBoxStyle.Exclamation, Title:="Missing folder")
Directory.CreateDirectory(destinationPath)
End If
Dim totalFiles As Integer = Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories).Count
Dim fileCount As Integer = 1
For Each filePathString As String In Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories)
Dim fileInfoItem As New FileInfo(filePathString)
Dim newFilePath As String = Path.Combine(destinationPath, fileInfoItem.Name)
If SourceDir.Exists And Not SourceDir.Name = skipDir Then
If File.Exists(newFilePath) Then
Dim result As Integer = MsgBox("File already exists in destination folder. Do you want to overwrite it?", MsgBoxStyle.YesNo, Title:="File already in folder")
If result = DialogResult.No Then
Continue For
ElseIf result = DialogResult.Yes Then
statusText = "Replacing found image"
BackgroundWorker1.ReportProgress(count, statusText)
File.Copy(filePathString, newFilePath, True)
End If
Else
File.Copy(filePathString, newFilePath)
End If
End If
fileCount = +1
Next
Catch ex As Exception
MsgBox("An error has occured. Please contact the system administrator. Exception: " & ex.Message)
End Try
End Sub

FTP Client uploads only 0KB files

I am having a small problem with my FTP client.
Choosing a file works, renaming that file with 4 variables works.
It's the upload that is causing me trouble.
Whenever a file is uploaded to the FTP server it says it is 0KB.
I am thinking of 2 possible problems:
Visual studio tells me that the variable file is used before it has been assigned a value, to make sure it isn't null i did the following.
Dim file As Byte()
If (Not file Is Nothing) Then
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
FileSystem.Rename(Filename, originalFile)
End If
This Takes care of any possible Errors.
The second one is fName, same warning as with file, and I took care of it the same way.
another possibility is that my code just takes the 4 variables and makes that into a file and uploads it, hence the 0KB size....
Here's my code:
Dim Filename As String
Dim originalFile As String
Private Function enumerateCheckboxes(ByVal path As String)
originalFile = path
Dim fName As String
For Each Control In Me.Controls
If (TypeOf Control Is ComboBox AndAlso DirectCast(Control, ComboBox).SelectedIndex > -1) Then
fName += CStr(Control.SelectedItem.Key) + "_"
End If
Next
Try
fName = path + fName.Substring(0, fName.Length - 1) + ".jpg"
Catch ex As Exception
MsgBox(ex.Message)
MsgBox("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
Return fName
End Function
Public Function OpenDialog()
Dim FD As OpenFileDialog = New OpenFileDialog()
FD.Title = "Selecteer een bestand"
FD.InitialDirectory = "C:\"
FD.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
FD.FilterIndex = 2
FD.RestoreDirectory = True
If FD.ShowDialog() = DialogResult.OK Then
Dim Filename As String = FD.FileName
Filename = StrReverse(Filename)
Filename = Mid(Filename, InStr(Filename, "\"), Len(Filename))
Filename = StrReverse(Filename)
MsgBox(enumerateCheckboxes(Filename))
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ip" & enumerateCheckboxes(Filename)), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("username", "password")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte
Try
Filename = OpenDialog()
If (Not Filename Is Nothing) Then
System.IO.File.ReadAllBytes(Filename)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
MessageBox.Show("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
If (Not Filename Is Nothing) Then
FileSystem.Rename(originalFile, Filename)
End If
Dim strz As System.IO.Stream = request.GetRequestStream()
If (Not file Is Nothing) Then
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
FileSystem.Rename(Filename, originalFile)
End If
End Sub
End Class
I have looked at multiple threads with the same problem as me.
Threads like this
But i dont believe this applies to my problem.
If you would be so kind to explain what i did wrong and how i can fix and avoid this in the future, my debugging is still a bit rough...
Thank you in advance!
Visual Studio is giving you that warning because you never assign anything to the file array. I think that on the line where you have:
System.IO.File.ReadAllBytes(Filename)
You really meant to have:
file = System.IO.File.ReadAllBytes(Filename)

VB.NET - Problems trying to write a textfile

I have problems when trying to delete/create/write to this file.
The error:
The process cannot access the file 'C:\Users\Administrador\AppData\Local\Temp\PlayList_temp.txt' because it is being used by another process.
The highlighted lines by debugger:
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
System.IO.File.Create(Temp_file)
(Any of two, if I delete one line, the other line takes the same error id)
The sub:
Public Sub C1Button2_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Not playerargs = Nothing Then
Dim Str As String
Dim Pattern As String = ControlChars.Quote
Dim ArgsArray() As String
Dim Temp_file As String = System.IO.Path.GetTempPath & "\PlayList_temp.txt"
Dim objWriter As New System.IO.StreamWriter(Temp_file)
Str = Replace(playerargs, " " & ControlChars.Quote, "")
ArgsArray = Split(Str, Pattern)
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
System.IO.File.Create(Temp_file)
For Each folder In ArgsArray
If Not folder = Nothing Then
Dim di As New IO.DirectoryInfo(folder)
Dim files As IO.FileInfo() = di.GetFiles("*")
Dim file As IO.FileInfo
For Each file In files
' command to writleline
'Console.WriteLine("File Name: {0}", file.Name)
'Console.WriteLine("File Full Name: {0}", file.FullName)
objWriter.Write(file.FullName)
objWriter.Close()
Next
End If
Next
If randomize.Checked = True Then
RandomiseFile(Temp_file)
End If
Process.Start(userSelectedPlayerFilePath, playerargs)
If autoclose.Checked = True Then
Me.Close()
End If
Else
MessageBox.Show("You must select at least one folder...", My.Settings.APPName)
End If
End Sub
First, File.Create creates or overwrite the file specified, so you don't need to Delete it before.
Second, initializing a StreamWriter as you do, blocks the file and therefore you can't recreate it after.
So, simply move the StreamWriter intialization after the File.Create, or better, remove altogether the File.Create and use the StreamWriter overload that overwrites the file
....
If Not playerargs = Nothing Then
....
Dim Temp_file As String = System.IO.Path.GetTempPath & "\PlayList_temp.txt"
Using objWriter As New System.IO.StreamWriter(Temp_file, false)
For Each folder In ArgsArray
If Not folder = Nothing Then
Dim di As New IO.DirectoryInfo(folder)
Dim files As IO.FileInfo() = di.GetFiles("*")
Dim file As IO.FileInfo
For Each file In files
' command to writleline
'Console.WriteLine("File Name: {0}", file.Name)
'Console.WriteLine("File Full Name: {0}", file.FullName)
objWriter.Write(file.FullName)
' objWriter.Close()
Next
End If
Next
End Using ' Flush, close and dispose the objWriter
....
Noticed also that you close the writer while still inside the loop, use the Using statement to close correctly the writer after the work is done.
The process cannot access the file 'C:\Users\Administrador\AppData\Local\Temp\PlayList_temp.txt' because it is being used by another process.
That means the file is opened or been used by another process.
Open your task manager and check if the file is there, then close it or simplex end the process.
I have had the same issue but I got it solved by closing the file.
Hope this helps!
From your details it seems that you are willing to delete if file exists and creates a new one.
I would suggest to remove this line:
System.IO.File.Create(Temp_file)
and move this line just over the streamwriter line:
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
Something like this would help you:
Partial code:
Dim Temp_file As String = System.IO.Path.GetTempPath & "\PlayList_temp.txt"
' Delete file if exists
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
' Create file for write.
Dim objWriter As New System.IO.StreamWriter(Temp_file)
Str = Replace(playerargs, " " & ControlChars.Quote, "")
ArgsArray = Split(Str, Pattern)
...
...
...