How to delete an image that is currently being used in a process - vb.net

So. I have an image that can be set as the background image on my vb app and when the user wants to change the image, I have it so that it fetches their chosen image from a showdialog and puts it into a specific filepath for the rest of the program to access. But, when the process is done more than once on its initial run (meaning there is no image in the directory yet) it gives and error saying the process cannot be completed due to ("C:\userdata" & ProteusLogin.txtUsername.Text & "" & "backgroundimage.jpg", "delete.jpg") process being in use.
Here is the code.
Private Sub RDBCustom_doubleclick(sender As Object, e As EventArgs) Handles RDBCustom.Click
RBLight.Checked = False
RBOriginal.Checked = False
RBDark.Checked = False
Dim openfiledialog1 As New OpenFileDialog
Try
My.Computer.FileSystem.CopyFile(openfiledialog1.FileName, "C:\userdata\" & ProteusLogin.txtUsername.Text & "\" & "backgroundimage.jpg")
Catch
If System.IO.File.Exists("C:\userdata\" & ProteusLogin.txtUsername.Text & "\" & "backgroundimage.jpg") = True Then
My.Computer.FileSystem.RenameFile("C:\userdata\" & ProteusLogin.txtUsername.Text & "\" & "backgroundimage.jpg", "delete.jpg")
System.IO.File.Delete("C:\userdata\" & ProteusLogin.txtUsername.Text & "\" & "delete.jpg")
My.Computer.FileSystem.CopyFile(openfiledialog1.FileName, "C:\userdata\" & ProteusLogin.txtUsername.Text & "\" & "backgroundimage.jpg")
End If
End Try
End Sub

Related

DataGridView - Data added does not stay after closing application

I have created a VB windows form Application with text boxes and a datagridview.
The idea is for the user to enter information onto the text boxes, and then click a button to save to the grid view. This works fine, but when closing the application and reopening the data is gone.
The below code is what i use to save the data to the grid view.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim rnum As Integer = DataGridView1.Rows.Add()
If Me.CheckBox1.Checked = True Then
Clipboard.SetText("Situation:" & vbNewLine & Me.TextBox1.Text & vbNewLine & vbNewLine & "Actions:" & vbNewLine & Me.TextBox2.Text & vbNewLine & vbNewLine & "Next Steps:" & vbNewLine & Me.TextBox3.Text & vbNewLine & vbNewLine & "Notes:" & vbNewLine & Me.TextBox4.Text)
Else
Clipboard.SetText("Situation:" & vbNewLine & Me.TextBox1.Text & vbNewLine & vbNewLine & "Actions:" & vbNewLine & Me.TextBox2.Text & vbNewLine & vbNewLine & "Next Steps:" & vbNewLine & Me.TextBox3.Text)
End If
DataGridView1.Rows.Item(rnum).Cells("Situation").Value = Me.TextBox1.Text
DataGridView1.Rows.Item(rnum).Cells("Actions").Value = Me.TextBox2.Text
DataGridView1.Rows.Item(rnum).Cells("NextSteps").Value = Me.TextBox3.Text
DataGridView1.Rows.Item(rnum).Cells("SupportingDocuments").Value = Me.TextBox4.Text
MsgBox("Added to Clipboard")
End Sub
The application is used by different users on different machine, so i want the gridview to have saved what that individual user has added.
I know im missing something easy, like adding a dataset but wouldnt this have to be on a static location used by everyone? And i also looked into xml files but cannot seem to find what im looking for.
Any help would be greatly appreciated.
All you have to do is to select your database in Project Explorer and navigate to its properties. In its properties, set "Copy to Output folder = Copy if Newer"
After trying to work around databases, but only seeming to get them static. I worked on using code to create xml files on the user profile, and then loading them.
This Link helped me alot

Continue for loop if a file is created in VB.NET

I'm using a COM interface to export animations from a third-party program. I'm sending an exporting COM command with script from my tool with a shell command.
There's a problem with when I send the animation export command to the third-party tool. It starts to export, but my tool is sending a second animation export command while the last one is not finished. How can I prevent from this situation?
I'd like to sending my shell command from the for loop after the file was created.
My code is like below.
Private Sub tlbCheckSolveEvaCtrl_exportmodeshape_Click(sender As Object, e As EventArgs) Handles tlbCheckSolveEvaCtrl_exportmodeshape.Click
Try
Dim strArgument As String
Dim strfilePathEV As String
Dim strfilePathANI As String
Dim strfilePathPIC As String
strfilePathEV = strProjMdlDir & My.Settings.txtCheckSolverOuputDir & strProjMdlName & ".ev.sbr"
strfilePathANI = strProjMdlDir & "\" & My.Settings.txtProjDirDOC & "\" & My.Settings.txtProjDirANI & "\"
strfilePathPIC = strProjMdlDir & "\" & My.Settings.txtProjDirDOC & "\" & My.Settings.txtProjDirPIC & "\"
For i As Integer = 0 To dgvCheckSolveEva.RowCount - 1
strArgument = strfilePathEV & " " & _
strfilePathANI & strProjMdlName & "_" & i & ".mpg" & " " & _
i
Shell(My.Settings.txtSpckDir & "simpack-post.exe -s qs_mode_shape.qs " & strArgument)
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I'd like to continue my for loop if strfilePathANI & strProjMdlName & "_" & i & ".mpg", the animation file was created, so I can start to export the next one.
The best way would be to use the .NET Process class and call the WaitForExit() method in order to wait for simpack-post.exe to close itself.
Shell() is an outdated function from the VB6-era which exists purely for partial backwards compatibility with that language. It shouldn't be used in new code.
Basic example:
Dim filePath As String = Path.Combine(My.Settings.txtSpckDir, "simpack-post.exe")
Process.Start(filePath, "-s qs_mode_shape.qs " & strArgument).WaitForExit()
The problem with this of course is that it might block the UI thread and thus cause it to freeze, depending on how long it takes for the process to exit. Therefore we should wrap it in a Task:
Dim c As Integer = dgvCheckSolveEva.RowCount - 1
Task.Run( _
Sub()
For i As Integer = 0 To c
strArgument = strfilePathEV & " " & _
strfilePathANI & strProjMdlName & "_" & i & ".mpg" & " " & _
i
Dim filePath As String = Path.Combine(My.Settings.txtSpckDir, "simpack-post.exe")
Process.Start(filePath, "-s qs_mode_shape.qs " & strArgument).WaitForExit()
Next
End Sub _
)
Just note that you cannot directly access the UI from within the task. If you want to do so you need to Invoke.
EDIT:
If you are targeting .NET Framework 3.5 or lower, or using VS 2008 or lower, tasks aren't available and we have to resort to using regular threads and/or regular methods instead of lamba expressions.
Note that the same rules apply, though - you cannot access the UI without invoking.
.NET 3.5 (or lower) using VS 2010 (and higher):
Dim c As Integer = dgvCheckSolveEva.RowCount - 1
Dim t As New Thread( _
Sub()
For i As Integer = 0 To c
strArgument = strfilePathEV & " " & _
strfilePathANI & strProjMdlName & "_" & i & ".mpg" & " " & _
i
Dim filePath As String = Path.Combine(My.Settings.txtSpckDir, "simpack-post.exe")
Process.Start(filePath, "-s qs_mode_shape.qs " & strArgument).WaitForExit()
Next
End Sub _
)
t.IsBackground = True
t.Start()
.NET 3.5 (or lower) using VS 2008 (or lower):
Private Sub tlbCheckSolveEvaCtrl_exportmodeshape_Click(sender As Object, e As EventArgs) Handles tlbCheckSolveEvaCtrl_exportmodeshape.Click
...your code...
Dim c As Integer = dgvCheckSolveEva.RowCount - 1
Dim t As New Thread(New ParameterizedThreadStart(AddressOf ExportAnimationsThread))
t.IsBackground = True
t.Start(c)
...your code...
End Sub
Private Sub ExportAnimationsThread(ByVal Count As Integer)
For i As Integer = 0 To Count
strArgument = strfilePathEV & " " & _
strfilePathANI & strProjMdlName & "_" & i & ".mpg" & " " & _
i
Dim filePath As String = Path.Combine(My.Settings.txtSpckDir, "simpack-post.exe")
Process.Start(filePath, "-s qs_mode_shape.qs " & strArgument).WaitForExit()
Next
End Sub

.DrawToBitmap Saved Image Wont Open In IE Browser

The code below saves a populated form as a .JPG image. However, it needs to be able to be opened in IE browser. Any other .JPG image not generated by the code opens and if I change the code to save as a .png it also opens in IE browser. Do I need to do anything special for .JPG/ .JPEG?
Code:
Private Sub btnImage_Click(sender As Object, e As EventArgs) Handles btnImage.Click
Dim dialog As New FolderBrowserDialog()
dialog.RootFolder = Environment.SpecialFolder.Desktop
dialog.SelectedPath = ""
dialog.Description = "Select Save Location"
If dialog.ShowDialog() = DialogResult.OK Then
Savepath = dialog.SelectedPath
SaveName = txtPN.Text
If Not SaveName = "" Then
Using bm As New Bitmap(HUD.pnlMain.Width, HUD.pnlMain.Height, Imaging.PixelFormat.Format16bppRgb555)
HUD.pnlMain.DrawToBitmap(bm, New Rectangle(0, 0, bm.Width, bm.Height))
bm.Save(Savepath & "\" & SaveName & ".JPG") '.PNG
End Using
MsgBox("Image was saved as " & SaveName & " at " & Savepath)
Else
Exit Sub
End If
Exit Sub
End If
End Sub
I get this:
Maybe you should try passing the format.
bm.Save(Savepath & "\" & SaveName & ".JPG", System.Drawing.Imaging.ImageFormat.Jpeg)
Also, you could use the Path class to create the full path of the file.

VB.net Delete a file which keeps getting replaced

I have written a VB.net executable that deletes a file then transfers a different one in it's place. An extract of the code is shown below. The problem is it fails every time due to the program that uses the file recreates it immediately after deletion.
How can I delete the file and prevent it being replaced? I cannot change anything about the program that's recreating it.
If IO.File.Exists(AMPDir & "AMP_DIR.DAT") = False Then
MsgBox("The following file is missing..." & vbCrLf & vbCrLf & " " & "AMP_DIR.DAT", MsgBoxStyle.Critical, "Error...")
Me.Close()
End
ElseIf IO.File.Exists(AMPDir & "AMP_DIR.DAT") = True And IO.File.Exists(LOGDir & "LOGIC.INF") = True Then
System.IO.File.Delete(AMPDir & "AMP_DIR.DAT")
System.IO.File.Copy(Path.GetDirectoryName(ConfigFile) & "\" & "AMP_DIR.DAT.IND", AMPDir & "AMP_DIR.DAT")
System.IO.File.SetAttributes(AMPDir & "AMP_DIR.DAT", FileAttributes.Normal)
End If

Moving a Sub and maintaining correct scope (replacing Me.)

I have a Sub within my application that is currently located within a userform called FRMPFC_folderCreatorWindow. For clarity of the overall application I wish to move this Sub from the userform into a Module called PFC_filesystemManipulation and call the Sub from there via a button in FRMPFC_folderCreatorWindow however, when I do this and run my code, an error is generated at the line:
For Each cCont In Me.Controls
I understand that this is because the Sub has been taken outside of the context of the form however, how do I maintain context without using Me.Controls? I'm guessing I need to reference the form and use FRMPFC_folderCreatorWindow.Controls but as most of the controls are nested within frames I'm unsure whether my current code acts upon the form or just the frame within which the button is located. Any help would be much appreciated.
Private Sub PFC_createFolders(Basepath, currentControl, parentFolder, parentGroup)
Dim cCont As Control
Dim createSubFolder As String
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
'Check if the project folder already exists and if so, raise an error and exit
MkDir Basepath & "\" & parentFolder
'Create the superceded documents folder in every 2nd generation folder
MkDir Basepath & "\" & parentFolder & "\" & "_Old versions"
For Each cCont In Me.Controls
If TypeName(cCont) = "CheckBox" Then
If cCont.GroupName = parentGroup Then
If cCont.Value = True Then
If cCont.Name <> currentControl Then
createSubFolder = cCont.Caption
NewFolder = Basepath & "\" & parentFolder & "\" & createSubFolder
If fs.folderexists(NewFolder) Then
'do nothing
Else
'Create 3rd generation folder
MkDir NewFolder
'Create the superceded documents folder in every 3rd generation folder
MkDir NewFolder & "\" & "_Old versions"
'Create hard-coded subfolders within Confirmit Exports
If createSubFolder = "Confirmit Exports" Then
MkDir Basepath & "\" & parentFolder & "\" & createSubFolder & "\Triple S"
MkDir Basepath & "\" & parentFolder & "\" & createSubFolder & "\Word Export"
MkDir Basepath & "\" & parentFolder & "\" & createSubFolder & "\Survey Definition"
MkDir Basepath & "\" & parentFolder & "\" & createSubFolder & "\Data"
MkDir Basepath & "\" & parentFolder & "\" & createSubFolder & "\Data" & "\" & "Early Data"
MkDir Basepath & "\" & parentFolder & "\" & createSubFolder & "\Data" & "\" & "Final Data"
End If
End If
End If
End If
End If
End If
Next cCont
End Sub
I've just experimented with this and replacing the Me.Controls with the following code works:
FRMPFC_folderCreatorWindow.Controls