Limited Multiselect in open file dialog? - vb.net

I want the user to have the option to select multiple files through openfiledialog which I have in my code, but then if the user selects a file from one folder he is then restricted to select another file only from this specific folder. What is the best way to approach to this problem?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim openfiledialog1 As New OpenFileDialog
With openfiledialog1
.Title = "Select your models"
.Filter = "Solidworks Files|*.sldprt;"
.Multiselect = True
End With
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
For Each mfile As String In openfiledialog1.FileNames
'' Add all filenames in a txt file, in a column
Next
End If
End Sub

As far as I know, OpenFileDialog doesn't offer a way to prevent the user from navigating to another directory.
One approach would be to create a class-level variable that holds the value of the recently used directory path. Then, whenever a new file is selected, you check its directory path against the one previously stored. If it matches, continue. If not, break the operation and report to the user.
Here's a complete example:
Private openFileDialog1 As New OpenFileDialog
Private modelsDirectory As String = Nothing
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
With openFileDialog1
.Title = "Select your models"
.Filter = "Solidworks Files|*.sldprt;"
.Multiselect = True
.FileName = Nothing
' Open the dialog and navigate to the previous direcoty by default.
.InitialDirectory = modelsDirectory
End With
If openFileDialog1.ShowDialog <> DialogResult.OK Then Exit Sub
Dim dirPath As String = IO.Path.GetDirectoryName(openFileDialog1.FileName)
If modelsDirectory IsNot Nothing AndAlso
Not dirPath.Equals(modelsDirectory, StringComparison.OrdinalIgnoreCase) Then
MessageBox.Show("Models must be selected from the following directory:" &
vbNewLine & modelsDirectory, "Restricted Directory")
Exit Sub
End If
' Store the value of the current directory path.
modelsDirectory = dirPath
For Each filePath As String In openFileDialog1.FileNames
' TODO: use the selected files as you see fit.
Next
End Sub
You might want to remove this restriction at some point (e.g., if you clear the list of selected files). You can achieve that by simply setting modelsDirectory to Nothing:
Private Sub ClearFilesList
' TODO: clear the files.
modelsDirectory = Nothing
End Sub

Related

How to overwrite a file in specific folder with a file in my program's resources

I have a file named "something.a binary extension" "not a txt extension" in my program's resources and the same file exists in another folder and named "Something.a binary extension" too.
I want to copy my resources file and replace the existing file with it.
My program has 2 button controls, one for browsing to get the path from OpenFileDialog1 and the other to copy my resources file and replace the existing file "Which have the same name" by it, and 1 TextBox to display the path.
My program has a manifest file to run as Adminstrator with level="highestAvailable.
I use this code:
Public Class Form1
Dim Path_of_folder As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
'getting the path
OpenFileDialog1.ValidateNames = False
OpenFileDialog1.CheckFileExists = False
OpenFileDialog1.CheckPathExists = True
OpenFileDialog1.FileName = "somthing.exe"
OpenFileDialog1.ShowDialog()
TextBox1.Text = System.IO.Path.GetFullPath(OpenFileDialog1.FileName)
TextBox1.Text = TextBox1.Text.Replace("somthing.exe", "").Trim()
Path_of_folder = TextBox1.Text 'we got the path
End Sub
Private Sub BtnCopy_Click(sender As Object, e As EventArgs) Handles BtnCopy.Click
FileCopy(My.Resources.somthing, Path_of_folder) ' this got Error when i use it, but the program can Run
End Sub
End Class

Saving listbox's file not just its name

Im working on my first injector in VB.NET.
Im trying to save the loaded dll in listbox, but it only saves the name.
I select the dll, inject, it saves my.settings, but once I reopen the injector it only saves the dll's name, not its path, so I have to browse and select it again
I was thinking about maybe I have to save openfiledialog or something but really got no clue
Inject button:
My.Settings.dll = New Specialized.StringCollection
My.Settings.dll.AddRange(dll.Items.Cast(Of String).ToArray)
My.Settings.Save()
My.Settings.process = SteamTextBox2.Text
My.Settings.Save()
On form load:
If My.Settings.dll IsNot Nothing Then dll.Items.AddRange(My.Settings.dll.Cast(Of String).ToArray)
The problem with this the injector only needs the dll's name without path
Dim ExeName As String = IO.Path.GetFileNameWithoutExtension(Application.ExecutablePath)
Private Sub Inject()
pszLibFileRemote = OpenFileDialog1.FileName
End Sub
OpenFileDialog1.Filter = "DLL (*.dll) |*.dll"
OpenFileDialog1.ShowDialog()
OpenFileDialog1.ToString()
If IO.File.Exists(OpenFileDialog1.FileName) Then
Dim TargetProcess As Process() = Diagnostics.Process.GetProcessesByName(SteamTextBox2.Text)
If TargetProcess.Length = 0 Then
...
Else
Call Inject()
I want it to load the actual selected file not just it's name
Nothing is functionally wrong with your code. I guess the problem is with how you load the paths into the listbox in the first place. Here is some code to do that.
Add a new button called LoadButton, then this code for the handler
Private Sub LoadButton_Click(sender As Object, e As EventArgs) Handles LoadButton.Click
Dim filenames As IEnumerable(Of String)
Using dialog As New OpenFileDialog
dialog.Filter = "Application extensions (*.dll)|*.dll|All files (*.*)|*.*"
dialog.Multiselect = True
Select Case dialog.ShowDialog()
Case DialogResult.OK
filenames = dialog.FileNames
Case Else
filenames = Nothing
End Select
End Using
filenames = filenames.Select(Function(fn) System.IO.Path.GetFileName(fn))
If filenames?.Any() Then dll.Items.AddRange(filenames.ToArray())
End Sub
This will put the full path into the listbox. Does this solve the problem?

Moving files into new folder using VB

I have one Log file that keep a full path for *.docx extension every time it's created. The problem is I don't know how to split the file's name from the full path. Before move it, I can select which Path that have been created using CheckedListBox and move it to target folder.
For example in my Log File I store (file has been created: C:\Users\AsrahLim\Desktop\New Microsoft Word Document.docx), all I need is the file's name "New Microsoft Word Document.docx" and move it to new folder .
This is my target folder: C:\Users\AsrahLim\Google Drive. Below is my code.
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckedListBox1.Items.Add("Select/UnSelect All")
CheckedListBox1.CheckOnClick = True
Dim FILE_NAME As String = "C:\Users\AsrahLim\Desktop\LogFile.txt"
If System.IO.File.Exists(FILE_NAME) Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek() <> -1
CheckedListBox1.Items.Add(objReader.ReadLine())
btnSave.Enabled = True
Loop
Else
MessageBox.Show("File Does Not Exist")
Close()
End If
End Sub
Private Sub btnSave_Click(sender As System.Object, e As System.EventArgs) Handles btnSave.Click
If CheckedListBox1.CheckedItems.Count <> 0 Then
For i As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
Dim SourcePath As String = CheckedListBox1.SelectedItem
Dim MoveLocation As String = "C:\Users\AsrahLim\Google Drive"
SourcePath = SourcePath.Substring(SourcePath.LastIndexOf("- ") + 1)
If File.Exists(SourcePath) = True Then
File.Move(SourcePath, MoveLocation)
MsgBox("File Moved")
Else
MsgBox("File Not move")
End If
Next
End If
End Sub
Private Sub btnCancel_Click(sender As System.Object, e As System.EventArgs) Handles btnCancel.Click
Close()
End Sub
End Class
Don't try to implement your own logic for path manipulations. Use the shared Path class in System.IO instead.
Dim filename As String = Path.GetFileName(SourcePath)
Then you can construct the new path name with
Dim destinationPath As String = Path.Combine(MoveLocation, filename)
Also, test if the file exists in the destination location as well and delete it if it exists.
If File.Exists(SourcePath) Then
Dim filename As String = Path.GetFileName(SourcePath)
Dim destinationPath As String = Path.Combine(MoveLocation, filename)
If File.Exists(destinationPath) Then
File.Delete(destinationPath)
End If
File.Move(SourcePath, destinationPath)
MsgBox("File Moved")
Else
MsgBox("File Not move")
End If
A side note: I don't like statements like If File.Exists(SourcePath) = True Then. Often people think that an If-statement requires a comparison. This is not true. All it needs is a Boolean expression, i.e. an expression returning either True or False. File.Exists(SourcePath) is an expression which does exactly this. The additional = True doesn't change anything and is superfluous, because if File.Exists(SourcePath) returns True then True = True is True and if File.Exists(SourcePath) returns False then False = True is False. = True is a neutral operation as is * 1 for numbers. You don't say Foo(1 * x), you just say Foo(x).
Very simple in your log you could store with a delimiter for instance:
New File Created*C:\test.docx
The star symbol is a banned character in file name so you can be sure it wont be in the path. After this you can just do
Dim data() As String
data = Split(File.ReadAllText(LogFile.txt), StringSplitOptions.RemoveEmptyEntries)
File.Move(data(1), Path.Combine(MoveLocation , Path.GetFileName(data(1)))
Ideally you just shouldn't store files a bit everywhere on your computer and use distinct folders.

Import CSV file to database using VB

I need to import the information from a CSV txt file to a database using the DataGridView in my form. The application should allow the user to open a .txt file and then update the DataGridView table in my form. I am able to get the file, but am unable to update the grid using the file. I can update textboxes, but cannot figure out how to update the grid. Can anyone help me out with this?
Imports Microsoft.VisualBasic.FileIO
Imports System.IO
Public Class Form1
Private fileToOpen As String 'the file to be opened and read
Private responseFileDialog As DialogResult 'response from OpenFileDialog
Private myStreamReader As StreamReader 'the reader object to get contents of file
Private myStreamWriter As StreamWriter 'the writer object to save contents of textbox
Private myTextFieldParser As TextFieldParser ' To parse text to searched.
Dim myDataAdapter As OleDb.OleDbDataAdapter
Dim myString() As String
Dim myRow As DataRow
Private Sub PeopleBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles PeopleBindingNavigatorSaveItem.Click
Me.Validate()
Me.PeopleBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.MyContactsDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MyContactsDataSet.People' table. You can move, or remove it, as needed.
Me.PeopleTableAdapter.Fill(Me.MyContactsDataSet.People)
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
Dim fileContentString As String 'contents of the file
Dim update As New OleDb.OleDbCommandBuilder(myDataAdapter)
'Dim myRow As DataRow
'set the properties of the OpenFileDialog object
OpenFileDialog1.InitialDirectory = My.Computer.FileSystem.CurrentDirectory
OpenFileDialog1.Title = "Select File to View..."
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
'responseFileDialog contains holds the response of the user (which button they selected)
responseFileDialog = OpenFileDialog1.ShowDialog()
'check to see if the user select OKAY, if not they selected CANCEL so don't open anything
If (responseFileDialog <> System.Windows.Forms.DialogResult.Cancel) Then
'make sure there isn't a file already open, if there is then close it
If (myStreamReader IsNot Nothing) Then
myStreamReader.Close()
'TextBoxFileOutput.Clear()
End If
'open the file and read its text and display in the textbox
fileToOpen = OpenFileDialog1.FileName
myStreamReader = New StreamReader(OpenFileDialog1.FileName)
initTextFieldParser()
'loop through the file reading its text and adding it to the textbox on the form
Do Until myStreamReader.Peek = -1
fileContentString = myStreamReader.ReadLine()
'Try
' myTextFieldParser = New TextFieldParser(fileToOpen)
' myTextFieldParser.TextFieldType = FieldType.Delimited
' myTextFieldParser.SetDelimiters(",")
'Catch ex As Exception
' MessageBox.Show("Cannot Open File to Be Read!")
'End Try
myTextFieldParser.TextFieldType = FieldType.Delimited
myString = TextFieldParser.NewLine()
myRow.Item("FirstName") = myString(1)
MyContactsDataSet.Tables("People").Rows.Add(myRow)
PeopleTableAdapter.Update(MyContactsDataSet)
'TextBoxFileOutput.AppendText(fileContentString)
'TextBoxFileOutput.AppendText(Environment.NewLine)
Loop
'close the StreamReader now that we are done with it
myStreamReader.Close()
'SaveToolStripMenuItem.Enabled = True
End If
End Sub
Private Sub initTextFieldParser()
'Close myTextFieldParser in case the user is surfing through the records and then
'decides to search for a particular last name --> Basically start searching from beginning of the file
If (myTextFieldParser IsNot Nothing) Then
myTextFieldParser.Close()
End If
Try
myTextFieldParser = New TextFieldParser(fileToOpen)
myTextFieldParser.TextFieldType = FieldType.Delimited
myTextFieldParser.SetDelimiters(",")
Catch ex As Exception
MessageBox.Show("Cannot Open File to Be Read!")
End Try
End Sub
End Class
updating gridview with your file content
Import System.IO as we gonna need StreamReader
Using reader As New StreamReader("filepath")
DataGridView1.Columns.Add("col1",reader.ReadToEnd())
End Using
check this out!

select multiple files and load the file names to "Checked List Box"

I need to: open the file dialog box when a button clicked, and then I'll select multiple files, then click ok, then the files will appear on Checkedlistbox1. And I want the dialog box to remember the folder path which I browsed last (so when I click that button again, it will take me to that location). But when I just run "openfiledialog" I can't select multiple files, and when I add further code, the program gives errors. Please shed some light here. :)
Dim fbd As New OpenFileDialog With { _
.Title = "Select multiple files", _
.FileName = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)}
If fbd.ShowDialog = DialogResult.OK Then
CheckedListBox1.Items.AddRange(Array.ConvertAll(IO.Directory.GetFiles(fbd.FileNames), Function(f) IO.Path.GetFileName(f)))
End If
I used a List(of String) in my test, you can change it so as to meet your needs.
Dim fbd As New OpenFileDialog With { _
.Title = "Select multiple files", _
.Multiselect = True, _
.FileName = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)}
If fbd.ShowDialog = DialogResult.OK Then
CheckedListBox1.AddRange(fbd.FileNames.Select(Function(f) IO.Path.GetFileName(f)))
End If
EDIT
I edited my code so as to use an object. The following is an example. You can use it to create the needed object for CheckBoxList
Public Property CheckedListBox1 As New List(Of TestClass)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fbd As New OpenFileDialog With { _
.Title = "Select multiple files", _
.Multiselect = True, _
.FileName = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)}
If fbd.ShowDialog = DialogResult.OK Then
CheckedListBox1.AddRange(fbd.FileNames.Select(Function(f) New TestClass With {.Name = IO.Path.GetFileName(f)}))
End If
End Sub
Public Class TestClass
Public Property Name As String
End Class
EDIT 2
Dim fbd As New OpenFileDialog With { _
.Title = "Select multiple files", _
.Multiselect = True, _
.FileName = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)}
If fbd.ShowDialog = DialogResult.OK Then
CheckedListBox1.Items.AddRange(fbd.FileNames.Select(Function(f) IO.Path.GetFileName(f)).ToArray)
End If
Use InitialDirectory property and a temporarily global string variable to remember your last open directory.
Dim LastDir As String = ""
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim fbd As New OpenFileDialog
If LastDir = "" Then Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
With fbd
.Title = "Select multiple files" ' Title of your dialog box
.InitialDirectory = LastDir ' Directory appear when you open your dialog.
.Multiselect = True 'allow user to select multiple items (files)
End With
If fbd.ShowDialog() = Windows.Forms.DialogResult.OK Then ' check user click ok or cancel
LastDir = Path.GetDirectoryName(fbd.FileName) 'Update your last Directory.
' do your stuf here i.e add selected files to listbox etc.
For Each mFile As String In fbd.FileNames
CheckedListBox1.Items.Add(mFile, True)
Next
End If
this will remember your last open directory while your program is running/alive.
If you want your dialog box always remember last opened directory store LastDir in your program settings or in computer registry.