VB.net Could not find directory - vb.net

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

Related

UWP epPlus - choose directory to save

I am making an application in vb using UWP and epPlus along with it to save the current database to an excel file. I would create a pop up dialog box that will allow the client to select the directory they want to save the excel file to. There isn't a "Savefiledialog" in UWP... Ideas?
UPDATE
I tried to use FileSavePicker: if I save it in the principal directory (C:\, Desktop, Documents ...) epPlus doesn't work, but if I save it in another directory (D:\, USB...) it workes... How can I save it in the principal directory?
I post my code here:
Private Async Sub ButtonXls_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
OutputTextBlock.Text = ""
Dim savePicker As FileSavePicker = New FileSavePicker()
savePicker.SuggestedStartLocation = PickerLocationId.Desktop
savePicker.FileTypeChoices.Add("Microsoft Excel", New List(Of String)() From {
".xlsx"
})
savePicker.SuggestedFileName = "Riepilogo_Test"
Dim file As StorageFile = Await savePicker.PickSaveFileAsync()
If file IsNot Nothing Then
CachedFileManager.DeferUpdates(file)
Dim ExcelPkg As ExcelPackage = New ExcelPackage()
Dim wsSheet1 As ExcelWorksheet = ExcelPkg.Workbook.Worksheets.Add("Sheet1")
Using Rng As ExcelRange = wsSheet1.Cells(2, 2, 2, 2)
Rng.Value = "Text file on Excel here"
Rng.Style.Font.Size = 16
Rng.Style.Font.Bold = True
Rng.Style.Font.Italic = True
End Using
wsSheet1.Protection.IsProtected = False
wsSheet1.Protection.AllowSelectLockedCells = False
Dim filePath As FileInfo = New FileInfo(file.Path)
ExcelPkg.SaveAs(filePath)
Dim status As FileUpdateStatus = Await CachedFileManager.CompleteUpdatesAsync(file)
If status = FileUpdateStatus.Complete Then
OutputTextBlock.Text = "File " & file.Name & " was saved."
ElseIf status = FileUpdateStatus.CompleteAndRenamed Then
OutputTextBlock.Text = "File " & file.Name & " was renamed and saved."
Else
OutputTextBlock.Text = "File " & file.Name & " couldn't be saved."
End If
Else
OutputTextBlock.Text = "Operation cancelled."
End If
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.

Winform not closing Why?

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

VB.NET Parameter is not valid

I have used dotnetbar devcomponents advanced treeview to create multiple directory trees for one of my projects. Functionality wise, everything is working fine.
I have now added images to the directory file nodes (e.g. pdf image if its a pdf file) and published the application. The application runs without any errors first time on any machine, but once I close this File Management form (I have a control panel form with buttons that is the initial startup form. The buttons take me to other forms. On button click, it hides the control panel and displays the corresponding form through showdialog - File Management form is one of those buttons) and reopen it again - I get the following error:
parameter_is_not_valid
It then fails to load the nodes and after a couple of tries, Microsoft .Net Framework window appears and ends the application.
I get the images from my resource file. Please see the code for LoadAllSubDirectoriesFiles where the error occurs:
Private Sub LoadAllSubDirectoriesFiles(ByVal uParent As DevComponents.AdvTree.Node)
' Initialise Error Checking
Dim uStackframe As New Diagnostics.StackFrame
Dim ufile As IO.FileInfo = Nothing
Try
If uParent.Name.Length <> 248 Then
Dim files As IO.FileInfo() = uParent.Tag.GetFiles()
For Each file As IO.FileInfo In files
If (Not file.Attributes.ToString.Contains("Hidden")) Then
Dim uNode As DevComponents.AdvTree.Node = New DevComponents.AdvTree.Node()
uNode.Tag = file
uNode.Name = file.FullName.ToLower
uNode.Text = file.Name
If file.Extension = ".msg" Then
uNode.Image = My.Resources.Resources.Mail3
ElseIf file.Extension = ".txt" Then
uNode.Image = My.Resources.Resources.Document
ElseIf file.Extension = ".pdf" Then
uNode.Image = My.Resources.Resources.pdf
ElseIf file.Extension = ".doc" OrElse file.Extension = ".docx" Then
uNode.Image = My.Resources.Resources.doc
ElseIf file.Extension = ".xlsx" Then
uNode.Image = My.Resources.Resources.excel
ElseIf file.Extension = ".pub" Then
uNode.Image = My.Resources.Resources.publisher
ElseIf file.Extension = ".pptx" Then
uNode.Image = My.Resources.Resources.powerpoint
ElseIf file.Extension = ".bmp" OrElse file.Extension = ".png" OrElse file.Extension = ".jpg" OrElse file.Extension = ".gif" OrElse file.Extension = ".tif" Then
uNode.Image = My.Resources.Resources.bitmap_image
ElseIf file.Extension = ".zip" OrElse file.Extension = ".rar" Then
uNode.Image = My.Resources.Resources.zip
Else
uNode.Image = My.Resources.Resources.unknown
End If
uNode.DragDropEnabled = True
uParent.Nodes.Add(uNode)
End If
Next
End If
Catch ex As Exception
' Catch Error
If Err.Number <> 0 Then
WriteAuditLogRecord(uStackframe.GetMethod.DeclaringType.FullName, uStackframe.GetMethod.Name.ToString, "Error", ex.Message & vbCrLf & vbCrLf & ex.StackTrace, 0)
MsgBox("System Error Ref: " & sAuditID & vbCrLf & uStackframe.GetMethod.DeclaringType.FullName & " / " & uStackframe.GetMethod.Name.ToString & vbCrLf & ex.Message & vbCrLf & vbCrLf & ex.StackTrace & Chr(13) & sErrDescription & vbCrLf & vbCrLf & "Press Control + C to copy this error report", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "Business Management System - Unexepected Error Ref: " & sAuditID)
End If
Finally
' CleanUp
End Try
End Sub
I have spent 2 days now trying to figure out the cause and fix for this problem. There were posts that talked about the image being disposed and not being able to retrieve the image reference [ http://blog.lavablast.com/post/2007/11/29/The-Mysterious-Parameter-Is-Not-Valid-Exception.aspx ] , cloning the image before disposing etc.
I have given disposing and cloning a go, but the error still stands. Been trying couple of other things, but still unsuccessful.
Any suggestions to what is wrong?
EDIT 1
Before closing the form, I clear all the treenodes and then use Me.Close()
Private Sub tsbClose_Click(sender As Object, e As EventArgs) Handles tsbClose.Click
atRootFolder.Nodes.Clear()
atAllDirectories.Nodes.Clear()
atScannedFiles.Nodes.Clear()
atFiles.Nodes.Clear()
atInbox.Nodes.Clear()
atSent.Nodes.Clear()
Me.Close()
End Sub
EDIT 2
My treeviews have hundreds of nodes, child nodes etc. Please see the image of my File Management form ( this is the first time it was loaded, no errors) I had to hide the text due to client confidentiality, but I hope it makes sense. Each image is a node.
imgur.com/QQ2FzFV
I had tried to use GC.Collect to see if it works, and surprising it did. Sadly it worked on one machine and didn't in another. Therefore, instead of calling images directly from my resources, I have stored all required images in an image list which I have attached to my treeviews. It's working like a charm.

Move files with certain extensions only

I'm currently using the Directory.Move method to copy files from one location to another. What i would like to do is only move files with certain extensions (.dbf, .ini & .txt). If the original folder doesn't contain any of these files then i just want to create an empty directory
Current code I'm using is...
Dim n As Integer
If lb1.SelectedItems.Count = 0 Then Exit Sub
For n = 0 To UBound(AllDetails)
If AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps = lb1.SelectedItem Then
If Not My.Computer.FileSystem.DirectoryExists(aMailbox & "\" & AllDetails(n).uFile) Then
Directory.Move(zMailbox & AllDetails(n).uFile, aMailbox & "\" & AllDetails(n).uFile)
lb3.Items.Add(AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps)
Else
lb3.Items.Add(AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps)
Exit Sub
End If
End If
Next
All the variables are declared and this works but moves the entire folder contents
One way to approach this is to use each extension as a search pattern for File.GetFiles, then use Directory.Move on each file returned. Something like this might help:
For Each OldFile As String In (From s In {".dbf", ".ini", ".txt"}
From f In Directory.GetFiles(zMailbox & AllDetails(n).uFile, s)
Select f)
Directory.Move(OldFile, aMailbox & "\" & AllDetails(n).uFile & "\" & Path.GetFileName(OldFile))
Next
if what you want is certain file extensions only? well Open File Dialog can filter that for you
Let's say you call this operation with a button click:
Dim fd As OpenFileDialog = New OpenFileDialog()
fd.Title = "Open File Dialog"
fd.InitialDirectory = "the initial directory you want to look at first"
'this filters the available files to be opened!
fd.Filter = "dbf files|*.dbf*|ini files|*.ini*|Text files|*.txt*"
fd.FilterIndex = 2 'set's the default files to open first as .ini
fd.RestoreDirectory = True
If fd.ShowDialog() = Windows.Forms.DialogResult.OK Then
'Copy the file to the location using the copyer subroutin
resulta.Text = fd.FileName.ToString
Copyer(fd.FileName.Tostring, "the location where you want to copy")
End If
End Sub
Now for the copying of the file, have a look at this subroutine. This subroutine checks first if the file exists. If it does, it deletes it, then copies the new file.
Public Sub Copyer(ByVal theFile As String, ByVal Lokasyon As String)
Try
Dim resultpath As String = Lokasyon
If System.IO.File.Exists(resultpath) = True Then
System.IO.File.Delete(resultpath)
'this deletes the file so you can overwrite it.
End If
My.Computer.FileSystem.CopyFile(theFile, resultpath)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Please let me know if this has helped you.