Winform not closing Why? - vb.net

I have some code to save a log in my FormClosing event that was working ok until I add code to create a Directory if it not exist such directory.
Now if I add the commented lines the application doesn't close.
I don't understand why.
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
TmrReporte.Stop()
WriteRTBLog("Finalizacion del programa. - Version " & Me.ProductVersion, Color.Blue)
Dim Fecha As String
Fecha = Now.ToShortDateString & "-" & Now.ToLongTimeString
Fecha = Fecha.Replace("/", "")
Fecha = Fecha.Replace(":", "")
Dim PathArchivo As String = Application.StartupPath & "\Logs\" & Fecha & ".logout"
'If (Not System.IO.Directory.Exists(PathArchivo)) Then
' System.IO.Directory.CreateDirectory(PathArchivo)
'End If
RTB_Log.SaveFile(PathArchivo, System.Windows.Forms.RichTextBoxStreamType.RichText)
End Sub

The problem is with the string format of the directory, you use PathArchivo for both the directory and the file while you actually only need to create the directory without filename for the directory creation:
Dim PathDir As String = Application.StartupPath & "\Logs" 'use only directory string here
Dim PathArchivo As String = Application.StartupPath & "\Logs\" & Fecha & ".logout" 'note that this is file name with .logout extension
If (Not System.IO.Directory.Exists(PathDir)) Then 'creates directory without .logout
System.IO.Directory.CreateDirectory(PathDir)
End If
RTB_Log.SaveFile(PathArchivo, System.Windows.Forms.RichTextBoxStreamType.RichText)
Note that your PathArchivo is a file path with logout extension

Related

Making a program that zip files but having error The process cannot access the file because it is being used by another process

I am trying to make a program that will zip all the files in the same folder.
But I'm having issues with it. It's giving me an error saying the file is being used by another process.
Private Sub btnZip_Click(sender As Object, e As EventArgs) Handles btnZip.Click
Dim extension As String = txtExtension.Text
Dim paths As String = Application.StartupPath
Dim files As String() = Directory.GetFiles(paths, "*.*")
For Each file As String In files
Dim fileName As String = path.GetFileNameWithoutExtension(file)
Dim index As Integer = fileName.IndexOf("_")
If index >= 0 Then
fileName = fileName.Substring(0, index)
End If
ZipFile.CreateFromDirectory(Path.GetDirectoryName(file), paths & "\" & fileName & ".zip", CompressionLevel.Optimal, False)
Next
MessageBox.Show("Files zipped successfully!")
End Sub
I just couldn't figure out what's causing the issue.
as seen in comment, you must exclude your running application from the file list :
add
If Path.GetFileName(file) = Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) Then Continue For
in for loop
Private Sub btnZip_Click(sender As Object, e As EventArgs) Handles btnZip.Click
Dim extension As String = txtExtension.Text
Dim paths As String = Application.StartupPath
Dim files As String() = Directory.GetFiles(paths, "*.*")
For Each file As String In files
If Path.GetFileName(file) = Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) Then Continue For
Dim fileName As String = Path.GetFileNameWithoutExtension(file)
Dim index As Integer = fileName.IndexOf("_")
If index >= 0 Then
fileName = fileName.Substring(0, index)
End If
ZipFile.CreateFromDirectory(Path.GetDirectoryName(file), paths & "\" & fileName & ".zip", CompressionLevel.Optimal, False)
Next
MessageBox.Show("Files zipped successfully!")
End Sub

Compressing a Folder Using Rar.exe via VB.NET?

I already extracted a folder with files from a RAR archive using the Unrar.exe I then want to edit the files within the extracted folder and then Re-rar that folder back into a password protected RAR archive. Either that, or append the existing RAR archive. Either way, the main goal is to update the files within the password protected archive. But I can't seem to figure out how to compress the folder again. My code as follows:
Imports System.IO
Public Class Form1
'establish the application directory and set it as a string to plugin later when needed
Dim MAINDIR As String = AppDomain.CurrentDomain.BaseDirectory
Private Sub UNRAR()
'if extracted folder does NOT exist then
If Not (System.IO.Directory.Exists(MAINDIR & "Credentials\")) Then
'set variables
Dim SourceFile As String = MAINDIR & "Credentials.rar"
Dim PassWord As String = "locker101"
Dim DestinationFolder As String = MAINDIR
'if extracted folder does not exist then
If Not IO.Directory.Exists(DestinationFolder) Then IO.Directory.CreateDirectory(DestinationFolder)
'unrar it and create extracted folder with the files
Dim p As New Process
p.StartInfo.FileName = MAINDIR & "UnRAR.exe"
p.StartInfo.Arguments = "-p" & PassWord & " x " & Chr(34) & SourceFile & Chr(34) & " " & Chr(34) & DestinationFolder & Chr(34)
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
p.Start()
End If
End Sub
Private Sub EDIT(ByVal ACCOUNT, ByVal USER, ByVal PASS, ByVal URL)
Do Until (System.IO.Directory.Exists(MAINDIR & "Credentials\"))
'does nothing on loop and keeps checking for the folder to exist
Loop
'confirms that the folder exists then begins to write to the file(s) inside
If (System.IO.Directory.Exists(MAINDIR & "Credentials\")) Then
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter(MAINDIR & "Credentials\" & ACCOUNT & ".txt", False)
file.WriteLine(USER)
file.WriteLine(PASS)
file.WriteLine(URL)
file.Close()
MsgBox("DONE")
Else
MsgBox("FAILED")
MsgBox("END existing")
MsgBox("END LOOP")
End If
APPENDRAR()
End Sub
Private Sub APPENDRAR()
End Sub
Private Sub DELETE()
'deletes the extracted folder, leaving behind only the password protected rar archive
My.Computer.FileSystem.DeleteDirectory(MAINDIR & "Credentials", False, False)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
UNRAR()
'sets textboxes' texts as strings then sends those values to the EDIT sub
Dim btn As Button = DirectCast(sender, Button)
Dim ACCOUNT As String = TB_account.Text
Dim USER As String = TB_user.Text
Dim PASS As String = TB_pass.Text
Dim URL As String = TB_url.Text
EDIT(ACCOUNT, USER, PASS, URL)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
End Sub
End Class
It should also be mentioned that I have the Unrar.exe and Rar.exe
files in the application folder. The same files found in the Winrar
directory. I added them to my project folder to use them.
A brief explanation of what is expected: The user will fill out 3 textboxes (username, password, website url) then they will click a button. The button takes the text in each textbox as values then creates strings of those values. It then passes these string values onto the sub which UNRARS the RAR archive, then once the folder is extracted, it either overwrites any existing file in that folder or creates a new one. Then after that, it should repack this newly edited folder back into a RAR archive with the same password as before, then deletes the extracted folder and the old RAR archive (UNLESS I can just append them back into the original archive, then I would not have to make an "updated" archive.)
UPDATE:
Dim SourceFile As String = MAINDIR & "Credentials\"
Dim PassWord As String = "locker101"
Dim DestinationFolder As String = MAINDIR
'if extracted folder does not exist then
'If Not IO.Directory.Exists(DestinationFolder) Then IO.Directory.CreateDirectory(DestinationFolder)
'unrar it and create extracted folder with the files
Dim p As New Process
Dim bbs As String = "-p" & PassWord & " u " & Chr(34) & MAINDIR & "ass.rar" & Chr(34) & " " & Chr(34) & SourceFile & Chr(34)
p.StartInfo.FileName = MAINDIR & "Rar.exe"
p.StartInfo.Arguments = bbs
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
p.Start()
This seems to work but it seems to not just add the "Credentials" folder but every folder leading up to it starting from "Projects".
I finally figured it out. Just in case anyone else needed the answer, here it is.
Dim p0 As New Process
Dim createo As String
createo = "-p" & <PASSWORD> & " u -ep " & Chr(34) & <arhive.rar> & Chr(34) & " " & Chr(34) & <FILE TO REPLACE> & Chr(34)
p0.StartInfo.FileName = "Rar.exe"
p0.StartInfo.Arguments = createo
p0.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
p0.Start()
Example for the string
createo = "-p" & TB_BIGKEY.Text & " u -ep " & Chr(34) & Form1.MAINDIR & "Users\" & TB_ID.Text & ".rar" & Chr(34) & " " & Chr(34) & Form1.MAINDIR & "Users\" & TB_ID.Text & ".txt" & Chr(34)
Which is read out 'tostring' as
-ppassyword u -ep "F:\Projects\PG\PG\bin\Debug\Users\Username.rar" "F:\Projects\PG\PG\bin\Debug\Users\Username.txt"
or <PASSWORD> <UPDATE> <EXLUDE PATHS> <RAR TO UPDATE> <FILE TO UPDATE WITH>
To not use a password, just remove the -ppassyword part.

Visual basic : Generic GDI+ error when saving file

When I executed my program I created in visual basic. I got a GDI+ error when I tried to save an image from a picturebox.
If I run it on the PC, where I created the program(windows 10), I don't have any problems. When I run it on 2 different windows 7 PC's, I got the error.
The mapped networkdrive is the same ( Z:\ ) and writeable.
Here is the code:
Private Sub SaveImage(ByVal pathToSaveTo As String)
Try
Using bmp As New Bitmap(Picimage.Image)
bmp.Save(pathToSaveTo, Drawing.Imaging.ImageFormat.Jpeg)
End Using
Catch ex As Exception
MessageBox.Show("An error occurred:" & vbCrLf & vbCrLf & _
ex.Message, "Error Saving Image File", _
MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End Try
End Sub
The button to start the action
Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim dt As String = My.Computer.FileSystem.SpecialDirectories.Desktop
Dim testOutput As String
testOutput = "Z:\" & naam & " " & Now.ToString("HH/mm/ss") & ".jpg"
SaveImage(testOutput)
nr.Focus()
End Sub
GDI is complaining about the filename you're using.
Here's the problem: testOutput = "Z:\" & naam & " " & Now.ToString("HH/mm/ss") & ".jpg"
You're generating a filename with slashes in the path. If those are meant to be directory names (a directory for each hour, minute and second respectively) then those directories need to ex that won't work as GDI will not create missing directories along a path for you. If the slashes are meant to be in the filename itself then it also won't work as slashes are not a valid filename character.
Change the slashes to underscores or hyphens or other characters allowed in filenames:
testOutput = "Z:\" & naam & " " & Now.ToString("HH_mm_ss") & ".jpg"

VB.net Could not find directory

This is the full code.
http://pastebin.com/cx9Tk0n3
I'm having a problem that, after downloading the mod, all works perfectly, the RAR file is located into the document folder while the extraxted content (#Mod) is under LauncherArma under Documents folder.
While clicking on the button to install the mod, starting from line 184, I've this error:
Private Sub FlatButton6_Click(sender As Object, e As EventArgs) Handles FlatButton6.Click
If My.Computer.FileSystem.DirectoryExists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\LauncherArma") Then
My.Computer.FileSystem.DeleteDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\LauncherArma", FileIO.DeleteDirectoryOption.DeleteAllContents)
End If
If My.Computer.FileSystem.FileExists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\LauncherArma\modsname.txt") Then
My.Computer.FileSystem.DeleteFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\LauncherArma\modsname.txt")
End If
My.Computer.FileSystem.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\LauncherArma")
UnRar(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\Addon.rar", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\LauncherArma")
Dim ligne As String
My.Computer.Network.DownloadFile("FTP ADDRESS. Hidden for security. Don't worry, the download files works!/modsname.txt", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\LauncherArma\modsname.txt")
Dim sr As New StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\LauncherArma\modsname.txt")
While sr.Peek <> -1
ligne = sr.ReadLine()
My.Computer.FileSystem.CopyDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\LauncherArma\" & ligne, directory & "\" & ligne, True)
End While
PictureBox1.Visible = True
FlatButton6.Visible = False
FlatProgressBar1.Visible = False
FlatLabel1.Visible = False
FlatLabel2.Visible = False
FlatLabel3.Visible = False
End Sub
I don't know how to solve this problem.
Waiting your reply!
Regards

Is there any tool to convert multiline text for Visual Studio 2008/2005?

Is there any tool that will convert a multiline text, to a compatible multiline string for Visual Studio 2008/2005?
For example:
line1
line2
line3
line4
Should become:
"line1" & _
"line2" & _
"line3" & _
"line4"
This kind of tool definitely falls in the do-it-yourself category. Start a new Windows Forms application. Paste the code shown below. Put a shortcut to the program on your desktop. To use it, drag a file from Explorer onto the form. Switch to Visual Studio and type Ctrl+V.
Public Class Form1
Public Sub New()
InitializeComponent()
Me.AllowDrop = True
End Sub
Protected Overrides Sub OnDragEnter(ByVal e As DragEventArgs)
If e.Data.GetDataPresent("FileDrop") Then e.Effect = DragDropEffects.Copy
End Sub
Protected Overrides Sub OnDragDrop(ByVal e As DragEventArgs)
Dim files = DirectCast(e.Data.GetData("FileDrop", False), String())
Dim txt As New System.Text.StringBuilder
Dim lines = System.IO.File.ReadAllLines(files(0))
For ix As Integer = 0 To lines.Length - 1
txt.Append("""" + lines(ix).Replace("""", """""") + """")
If ix < lines.Length - 1 Then txt.AppendLine(" & _")
Next
Clipboard.SetText(txt.ToString())
End Sub
End Class
The better mousetrap is to add the file as a resource instead of hard-coding the text.
Is this what you're looking for?
Dim testString As String = "line1" & vbCrLf & _
"line2" & vbCrLf & _
"line3" & vbCrLf & _
"line4"
Dim allLines() As String = Microsoft.VisualBasic.Strings.Split(testString, vbCrLf)
Dim strConverter As New System.Text.StringBuilder
For Each line As String In allLines
strConverter.Append("""" & line & """").Append(" & _").Append(vbCrLf)
Next
If allLines.Length > 0 Then strConverter.Length -= (" & _" & vbCrLf).Length
Dim convertedString As String = strConverter.ToString
A VS Macro for Pasting Long Text as String seems like perfect solution.