Download multiple files one by one as listed in a datagridview (vb.net code) - vb.net

Vb.net studio is comparivily new to (as a hobby when I have time) me so I need some help. to simply download a single file is easy I do that by the following code.
Try
' Make a WebClient.
Dim web_client As WebClient = New WebClient
' Download the file.
web_client.DownloadFile("TargetURLSite/MyFolder/" & "MyFile.exe", (Application.StartupPath & "\Plugins\" & MyFile.exe))
Catch ex As Exception
MessageBox.Show(ex.Message, "Download Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
Easy-Peazy...
But I now have a DataGridView column with file names of files I want to download. I thought that I could use a for each statement get the target file name from the first column of the DataGridView and execute the download function for each of the target files one by one but it dosnt seem to work I am lead to belive that its because the web client is stumbeling over its self still processing each download before being able to continue with the next.
For rowIndex = 0 To DataGridView1.RowCount - 1
'MsgBox("This cell is " & (DataGridView1.Rows(rowIndex).Cells("AppCol").Value.ToString))
Dim TargetApplication As String = (DataGridView1.Rows(rowIndex).Cells("AppCol").Value.ToString)
If My.Computer.FileSystem.FileExists(Application.StartupPath & "\Plugins\" & TargetApplication) Then
'File exists do nothing...
Else
'File dose not exist download to Plugins directory...
Try
' Make a WebClient.
Dim web_client As WebClient = New WebClient
' Download the file.
web_client.DownloadFile("TargetURLSite/MyFolder/" & TargetApplication, (Application.StartupPath & "\Plugins\" & TargetApplication))
Catch ex As Exception
MessageBox.Show(ex.Message, "Download Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
End If
Next
How do I fix this? I have a limited understanding of vb.net.

Related

How do I get a user to input a document and then save that document?

So I'm a bit stuck with my project, I am using Visual Studio and coding in Visual Basic, I am also using Microsoft Access with SQL if that helps at all.
What I need is to allow the user to select a document from an OpenFileDialog and to then save that document to the actual program so it is there when the program is next ran.
The following code is triggered on a button press, what I have so far is...
saveDocumentDialog.Filter = "Document Files|*.docx;*.doc;*.dot;*.txt;*.rtf;*.pdf;*.ppt;*.pptx;*.xls;*.xlsx"
saveDocumentDialog.FileName = "Untitled"
saveDocumentDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.Desktop
saveDocumentDialog.ShowDialog()
If saveDocumentDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
fullFilename = saveDocumentDialog.FileName
End If
Using openDocumentDialog As New SaveFileDialog
Dim filename As String = IO.Path.GetFileName(fullFilename)
openDocumentDialog.FileName = "Untitled"
openDocumentDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.Desktop
openDocumentDialog.Title = "Select Save Location"
openDocumentDialog.Filter = "All Files (*.*)|*.*"
If openDocumentDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
Try
My.Computer.FileSystem.CopyFile(fullFilename, openDocumentDialog.FileName)
Catch ex As Exception
MessageBox.Show("Could not copy the file." & Environment.NewLine & ex.Message, "Error copying file.", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
One way to do this is to designate a specific folder to the program(e.g. Public Documents), and save the files there and reload them from the folder when the program restarts. You could either hard code the path, or make a setting in the program for the user to specify a folder they would prefer.

VB.net, my code unable to run bat file

Dim app As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
If System.IO.Directory.Exists(app & "\Divers") Then
Try
Process.Start(app & "\Divers\b.bat")
cs.Text = "OK"
cs.Refresh()
Catch ex As Exception
eror.Text = "(B) Problems"
cs.Text = "error"
End Try
Try
Process.Start(app & "\Divers\Realtek\diver.exe")
d.Text = "OK"
Catch ex As Exception
DebugLog()
error.Text = "Driver Problems"
cs.Text = "error"
End Try
Try
Process.Start(app & "\Divers\a.bat")
CVS.Text = "OK"
Catch ex As Exception
error.Text = eror.Text & "(A) Problems"
cs.Text = "error"
End Try
And that is my code guys but the bat file is not working. Is opened but do nothing, if i open the bat file manual (with a mouse and double click logic!!!) its working. Please help
Your batch file may be working based on a working directory, and because you run the batch file with software that is in a different folder, the batch file's working directory does not match.
Put your software in the batch file folder and try again.

Startup Folder Permissions in VB.NET

I am building an app which installs all the company's bespoke software at the click of a button. Included in the list is an asset tracker/reporting tool which must run at startup for everyone. Our standard build (I have no control over this whatsoever) is Windows 10, and we also have some legacy Windows 7 machines around, but in each case the startup registry keys are locked down so I started to create shortcuts in C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup.
If the startup folder doesn't exist, then it creates the folder. Logged on as local admin, I can create the startup folder manually without UAC popping up, take ownership of the folder and assign Everyone to have modify access, creating a shortcut in there. When I log off/on, the software runs. However when I code this, I get permissions errors.
Here's the code:
Sub DetectFolders()
Dim sFolder1 As String = "C:\My Apps\"
Dim sFolder2 As String = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\"
Dim sFolder3 As String = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\"
If Not Directory.Exists(sFolder1) Then
Directory.CreateDirectory(sFolder1)
End If
If Not Directory.Exists(sFolder2) Then
Try
' create folder
TakeOwnership(sFolder3)
Application.DoEvents()
AddDirectorySecurity(sFolder3, "MyDomain\" & Environment.UserName, FileSystemRights.FullControl, AccessControlType.Allow)
Application.DoEvents()
Directory.CreateDirectory(sFolder2)
Application.DoEvents()
TakeOwnership(sFolder2)
' everyone has modify access // TEST
AddDirectorySecurity(sFolder2, "Everyone", FileSystemRights.Modify, AccessControlType.Allow)
Catch ex As Exception
MessageBox.Show(ex.Message, "Config", MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End Try
End If
End Sub
Sub TakeOwnership(ByVal sfolder As String)
' take ownership
Try
Dim ds As System.Security.AccessControl.DirectorySecurity
Dim account As System.Security.Principal.NTAccount
ds = System.IO.Directory.GetAccessControl(sfolder, System.Security.AccessControl.AccessControlSections.Owner)
account = New System.Security.Principal.NTAccount(System.Security.Principal.WindowsIdentity.GetCurrent.Name)
ds.SetOwner(account)
System.IO.Directory.SetAccessControl(sfolder, ds)
Application.DoEvents()
Catch ex As Exception
MessageBox.Show("" & ex.Message & "", "Take Ownership", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Sub AddDirectorySecurity(ByVal FileName As String, ByVal Account As String, ByVal Rights As FileSystemRights, ByVal ControlType As AccessControlType)
Try
' Create a new DirectoryInfoobject.
Dim dInfo As New DirectoryInfo(FileName)
' Get a DirectorySecurity object that represents the
' current security settings.
Dim dSecurity As DirectorySecurity = dInfo.GetAccessControl()
' Add the FileSystemAccessRule to the security settings.
dSecurity.AddAccessRule(New FileSystemAccessRule(Account, Rights, ControlType))
' Set the new access settings.
dInfo.SetAccessControl(dSecurity)
Catch ex As Exception
MessageBox.Show("" & ex.Message & "", "Add Security", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
The first two Errors that appear is: Attempted to perform an unauthorized Operation, generated from the first time that AddDirectorySecurity and TakeOwnership are called.
I then get an error which states:
Access to the path 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup' is denied.
This is generated from the directory.createdirectory line in DetectFolders sub
I'm rapidly beginning to run out of ideas to get this working. Is it something in my code? Am I missing something, or does windows 10 not work in this way. Any constructive help will be gratefully received.

Stop using a file

first i created a file by pressing on a label then i want to be able to delete it without restarting app (because it becomes in use)
code is
Dim UniWinDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "UniWin Activator Data")
Dim MsgIODat = Path.Combine(UniWinDataPath, "MessageIO.dat")
If File.Exists(MsgIODat) Then
'ERROR HERE
File.Delete(MsgIODat)
'''''''''''''''''''''
Dim clrdata = MessageBox.Show("Data Cleared.", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
ElseIf (Not (File.Exists(MsgIODat))) Then
Dim nodata = MessageBox.Show("There is no data to clear.", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
error: The process cannot access the file '(PATH)' because it is being used by another process.
i've searched and didn't find anyone talking about this in vb.net language
is there a way to let my app stop using it to delete the file?
You need to dispose the FileStream returned by the File.Create() Method.
When you create the file,
File.Create("file").Dispose()

PC cannot print to Email using Outlook

I am having a very strange problem where one of the computers in our company is unable to print an MS Access report and attach it to an email. I have done a lot of research however most of it doesn't apply to my case as this issue is happening only on one PC out of the 20+ we have in the company. This is a print screen of the error we are getting:
The code I am using is the following:
If PrintMode = "Email" Then
Dim mAcc As New Access.Application
Dim DefaultPrinterName As New String("")
Dim PDFPrinterName As New String("")
Maintain__Loading.Setup()
Try
mAcc.CloseCurrentDatabase()
mAcc.DoCmd.Close()
System.Runtime.InteropServices.Marshal.ReleaseComObject(mAcc)
mAcc = Nothing
Catch ex As Exception
End Try
Dim startInfo As New ProcessStartInfo("C:\Program Files (x86)\PDFCreator\PDFCreator.exe") 'starts PDF Creator so it can save the report to PDF
startInfo.WindowStyle = ProcessWindowStyle.Minimized
Process.Start(startInfo)
AttachmentName = "C:\PDFs\pdf.pdf" 'PDF has been set up to save all files as TestPrint.pdf
PDFPrinterName = "PDFCreatorDistribution"
'------ GETS DEFAULT PRINTER NAME -------
Dim oPS As New System.Drawing.Printing.PrinterSettings
Try
DefaultPrinterName = oPS.PrinterName
Catch ex As System.Exception
DefaultPrinterName = ""
Finally
oPS = Nothing
End Try
'sets PDFCreatorDistribution as default printer
Shell(String.Format("rundll32 printui.dll,PrintUIEntry /y /n ""{0}""", PDFPrinterName))
Try
If Not UCase(Trim(Database)) = "TEST" Then
mAcc.OpenCurrentDatabase("R:\Distribution\Access\Distribution-Reports.mde")
Else
mAcc.OpenCurrentDatabase("R:\Distribution\Access\Test-Distribution-Reports.mde")
End If
Catch ex As Exception
MsgBox(Err.Description)
End Try
If IO.File.Exists(AttachmentName) Then 'if file exists it deletes it
IO.File.Delete(AttachmentName)
End If
Select Case Trim(Grid.Rows(Grid.CurrentRow.Index).Cells("Passing1Type").Value.ToString)
Case "String"
mAcc.DoCmd.OpenReport(Trim(Grid.Rows(Grid.CurrentRow.Index).Cells("MacroName").Value.ToString), Access.AcView.acViewPreview, , Trim(Grid.Rows(Grid.CurrentRow.Index).Cells("Passing1").Value.ToString) & " = '" & Number & "'", Access.AcWindowMode.acWindowNormal)
Case "Numeric"
mAcc.DoCmd.OpenReport(Trim(Grid.Rows(Grid.CurrentRow.Index).Cells("MacroName").Value.ToString), Access.AcView.acViewPreview, , Trim(Grid.Rows(Grid.CurrentRow.Index).Cells("Passing1").Value.ToString) & " = " & Number & "", Access.AcWindowMode.acWindowNormal)
End Select
mAcc.DoCmd.PrintOut()
mAcc.Visible = True
mAcc.CloseCurrentDatabase()
mAcc.DoCmd.Close()
System.Runtime.InteropServices.Marshal.ReleaseComObject(mAcc)
mAcc = Nothing
Do While Not System.IO.File.Exists("C:\PDFs\pdf.pdf")
Threading.Thread.Sleep(2000) 'if doesn't exist, wait for 2 seconds
If Not System.IO.File.Exists("C:\PDFs\pdf.pdf") Then 'if doesn't exist, wait for another 2 seconds
Threading.Thread.Sleep(2000)
End If
If Not System.IO.File.Exists("C:\PDFs\pdf.pdf") Then 'if doesn't exist, wait for another 2 seconds
Threading.Thread.Sleep(2000)
End If
If Not System.IO.File.Exists("C:\PDFs\pdf.pdf") Then 'shows error message
MsgBox("Error creating PDF. Please try again")
Exit Do
End If
Loop
'sets default printer name
Shell(String.Format("rundll32 printui.dll,PrintUIEntry /y /n ""{0}""", DefaultPrinterName))
'saves file as
Dim saveFileDialog As New SaveFileDialog()
saveFileDialog.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*"
If saveFileDialog.ShowDialog() = DialogResult.OK Then 'if OK clicked
FileName = saveFileDialog.FileName 'get file name and move to new location/name
FileNameOnly = System.IO.Path.GetFileName(FileName)
Try
If IO.File.Exists(FileName) Then 'if file exists it deletes it before saving
IO.File.Delete(FileName)
End If
IO.File.Move(AttachmentName, FileName)
Catch ex As Exception
MsgBox(Err.Description)
Finally
Shell(String.Format("rundll32 printui.dll,PrintUIEntry /y /n ""{0}""", DefaultPrinterName))
End Try
Else 'user clicked cancel
FileName = ""
End If
Maintain__Loading.Dispose()
'GETS TO HERE AND AFTER THIS I GET THE ERROR MESSAGE DISPLAYED IN THE IMAGE ABOVE
If IO.File.Exists(FileName) Then
Try
Send_Email()
Catch ex As Exception
MsgBox(Err.Description)
End Try
Else
If Not FileName = "" Then MsgBox("An error has occured. Please try again")
End If
Shell(String.Format("rundll32 printui.dll,PrintUIEntry /y /n ""{0}""", DefaultPrinterName))
PhysicallyPrintedOrEmailed = True
End If 'Printmode = Email
I found a thread that I thought would solve my problem however unfortunately it didn't:
Unable to cast COM object - Microsoft outlook & C#
Any advice will be greatly appreciated
You have hardcoded the path to the program files location so if you are running this on a 32 bit machine it won't find the PDFCreator.exe.
Use Environment.GetFolderPath to find the path on the machine instead of hard coding it.`
Also it might help if you wrap the whole thing in a Try Catch block to see if there is an error somewhere you didn't expect
I have managed to solve this. Probably not the best way but we reinstalled Outlook and this solved the issue. We believe another program (most likely one that syncs Outlook contacts with phone) that has been installed has corrupted something. Thanks anyway :)