Go upper folder/directory VB.NET - vb.net

I'm making a file/folder explorer using a ListView, when clicking a folder, it shows its contents, but I can't make it go back to where I was before opening that folder, or better going on an upper folder. example I'm in D:\Folder1\Subfolder1\Subfolder and I want to go to its upper folder, I should be in D:\Folder1\Subfolder1, Everytime I click a button.
And i have this code but what it does is it replaces all paths, making it looks like this D:\Folder1 and I can't go back further. By the way the Textbox has a default value/text of D:\Folder.
this is my code:
Dim lvs As String
Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
lvs = ListView1.SelectedItems(0).Text.ToString
Form2.TextBox1.Text = Form2.TextBox1.Text & "\" & lvs
End Sub
Private Sub Button5_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Dim s As String = Form2.TextBox1.Text
s.Replace("\" & lvs, " ").TrimEnd()
End Sub
UPDATE
Hi, I updated my code, what I did was I'm putting the ListView items in an Array and I'm deleting the last element(the last folder path) and it works fine. but when I run my code, It only execute once and it cannot be repeated, what could be wrong?
code:
Dim lvs As New List(Of String)
Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
If ListView1.SelectedItems.Count > 0 Then
For Each item As ListViewItem In ListView1.SelectedItems
lvs.Add(item.Text)
Next
End If
Form2.TextBox1.Text = Form2.TextBox1.Text & "\" & ListView1.SelectedItems(0).Text
End Sub
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Label5.Text = Label5.Text.Replace("\" & lvs.ElementAt(lvs.Count - 1), "")
End Sub

You'd need to store the full path to the current folder in a string variable. You would then get the path of the parent folder by:
Dim parentPath As String = IO.Path.GetDirectoryName(currentPath)
Once you've done that you then need to make that new path the current path, which is probably what you weren't doing before. You probably just kept using the same base path to get the parent.
Here is an good sample : https://code.msdn.microsoft.com/windowsapps/Get-upper-folders-in-443e975a
Hopes this help you.

Simple way do this:
Dim path As String = #"C:\Folder1\Folder2\Folder3\Folder4"
Dim newPath As String = Path.GetFullPath(Path.Combine(path, #"..\"));
If you want to go 2level up then try #"..\..\"

Dim Child As String = "C:\Parent\Child"
Dim Parent As String = System.IO.Directory.GetParent(Child).FullName

Someone helped me with my updated code that i just have to put this lvs.RemoveAt(lvs.Count - 1), because i was only removing the item in the Label but not in the List(Of String)(that i thought is an Array, haha).
My Button should look like this:
Label5.Text = Label5.Text.Replace("\" & lvs(lvs.Count - 1), "")
lvs.RemoveAt(lvs.Count - 1)

Related

Remove line from text file which listed in list box

I have a text file(its hosts file)
I can add lines(domains) to the file through a text box.
When i click the 'Save' button, inputted value(domain) saves to the text(hosts) file with a 127.0.0.1 prefix. At the same time it shows that in a list box too(while showing it in list box, it won't show the prefix(127.0.0.1). It'll only show the value got from the text field)
What i need now is that,
When i click and select an item from the list box and press 'Remove' button, it needs to be removed from both the list box and the text(hosts) file.
Also, while removing the selected item from the list box, the prefix(127.0.0.1) also should be removed from the file without leaving an empty line.
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles BtnCustomDomainremove.Click
ListBox1.Items.Remove(ListBox1.SelectedItem)
Dim delLine As Integer = 1
Dim lines As List(Of String) = System.IO.File.ReadAllLines("C:\Windows\System32\drivers\etc\hosts").ToList
lines.RemoveAt(delLine - 1)
System.IO.File.WriteAllLines("C:\Windows\System32\drivers\etc\hosts", lines)
MessageBox.Show("URL removed from Block List !", "Custom Block List")
End Sub
Above code it removes the top value from file and selected one from list box.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lines As List(Of String) = System.IO.File.ReadAllLines("C:\Windows\System32\drivers\etc\hosts").ToList
Dim Findstring = IO.File.ReadAllText("C:\Windows\System32\drivers\etc\hosts")
Dim Lookfor As String = CStr("127.0.0.1" + ListBox1.SelectedItem)
If lines.Contains(Lookfor) Then
For i = 0 To Findstring.Length - 1
lines.Remove(Lookfor)
Next
System.IO.File.WriteAllLines("C:\Windows\System32\drivers\etc\hosts", lines)
ListBox1.Items.Remove(ListBox1.SelectedItem)
MessageBox.Show("URL removed from Block List !", "Custom Block List")
Else
MsgBox("string not found")
End If
End Sub
This code works for me, you might have to tweak it slightly to match your prefereneces however, it seems to find each occurunce (if there's more than one) of the selected item in listbox1 (if there's only one occurance you can remove the for loop.
Instead of Reading and Writing the file on every change to the list, save the list when the form closes. Read the file when the form opens and populate the list. While the form is open just add and remove list items as you normally would.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim path = "C:\Windows\System32\drivers\etc\hosts.txt"
Dim lines() As String = File.ReadAllLines(path)
'Substring(9) the characters in "127.0.0.1" are index 0-8 so we begin with index 9
'and return the rest of the string.
Dim TrimmedList = From line In lines
Select line.Substring(9)
For Each item In TrimmedList
ListBox2.Items.Add(item)
Next
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
Dim sb As New StringBuilder()
For Each item In ListBox2.Items
sb.AppendLine("127.0.0.1" & item.ToString)
Next
Dim path = "C:\Windows\System32\drivers\etc\hosts.txt"
File.WriteAllText(path, sb.ToString)
End Sub
Requires
Imports System.IO
Imports System.Text
try this code
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles BtnCustomDomainremove.Click
ListBox1.Items.Remove(ListBox1.SelectedItem)
Dim details As String = ""
For Each o As Object In ListBox1.Items
details += o.ToString + vbNewLine
Next
My.Computer.FileSystem.WriteAllText("C:\Windows\System32\drivers\etc\hosts", details, False)
MessageBox.Show("URL removed from Block List !", "Custom Block List")
End Sub

if the file not exits then return no error vb

I have start this application every things its work fine but i have a small bug but i can not find the solution to solve the error.
i have debug it and the error its because the file not exist
is there any way to me to populate my datagridview with all *.gif images From a directory and the check if its null or some thing like that.
What i mean is is there any way to my to populate all gif images found on the chose Directory?
in fact i have all ready try like this but i get one error "Provided column already belongs to the DataGridView control.
Well finaly i have found a solution to load all images from a directory to a datagridview programmatic
Here Is The Working Code
Public Class Form5
Private Sub addBtn_Click(sender As Object, e As EventArgs) Handles addBtn.Click
'Populate()
ShowImages()
End Sub
'CLEAR DATAGRIDVIEW
Private Sub clearBtn_Click(sender As Object, e As EventArgs) Handles clearBtn.Click
DataGridView1.Rows.Clear()
End Sub
'WHEN AN IMAGE IS CLICKED
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
MessageBox.Show("You Clicked Image At Col: " + e.ColumnIndex.ToString() + " Row: " + e.RowIndex.ToString())
End Sub
Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Public Sub ShowImages()
Dim directory As New System.IO.DirectoryInfo("C:\avitogifconverter\")
If directory.Exists Then
Dim pngFiles() As System.IO.FileInfo = directory.GetFiles("*.gif")
For Each pngFile As System.IO.FileInfo In pngFiles
If pngFile.Exists Then
Dim image = System.Drawing.Image.FromFile(pngFile.FullName)
Using image
Dim count = 1
' do something with the image like show in picture box
'CONSTRUCT IMG COLUMN
Dim imgCol As DataGridViewImageColumn = New DataGridViewImageColumn()
imgCol.HeaderText = "Photo"
imgCol.Name = "Col 1"
DataGridView1.Columns.Add(imgCol)
'CONSTRUCT ROWS
'FIRST ROW
Dim img As Image = System.Drawing.Image.FromFile(pngFile.FullName)
Dim row As Object() = New Object() {img, img, img}
DataGridView1.Rows.Add(row)
End Using
End If
Next
End If
End Sub
End Class
Using Directory.EnumerateFiles, you could do something like this:
Dim row = New List(Of Image)(3)
For Each filename In Directory.EnumerateFiles("C:\avitogifconverter", "*.gif")
row.Add(Image.FromFile(filename))
If row.Count = 3 Then
DataGridView1.Rows.Add(row.ToArray())
row.Clear()
End If
Next
If row.Count > 0 Then
DataGridView1.Rows.Add(row.ToArray())
row.Clear()
End If

Visual Studio rename files on a directory with cycle for and substitute it with text from a textbox

I need help with the cycle for, when program start should rename files on selected directory but it doesn't.
This is the code:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
FolderBrowserDialog1.ShowDialog()
Label4.Text = FolderBrowserDialog1.SelectedPath
Dim counter = FolderBrowserDialog1.SelectedPath
Label5.Text = counter.Count
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim basedir As String = FolderBrowserDialog1.SelectedPath
For counter As Integer = 0 To Int(Label5.Text)
My.Computer.FileSystem.RenameFile(basedir, TextBox1.Text + "x")
Next
End Sub
End Class
First of all, FolderBrowserDialog1.SelectedPath returns a normal string. Calling SelectedPath.Count will not give you how many files are in the directory, but how many character the string path consists of.
Secondly, calling RenameFile(basedir, ...) won't do anything since basedir points to a single directory - not the files in the directory.
In order to get a proper file count, AND iterate through the file names you'd have to use something like Directory.GetFiles(basedir).
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
FolderBrowserDialog1.ShowDialog()
Label4.Text = FolderBrowserDialog1.SelectedPath
Label5.Text = Directory.GetFiles(FolderBrowserDialog1.SelectedPath).Count
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim basedir As String = FolderBrowserDialog1.SelectedPath
Dim Files As String() = Directory.GetFiles(basedir) 'Declare an array that holds all file paths.
For counter As Integer = 0 To Files.Length - 1 'Minus one is important here, so that you won't get a "IndexOutOfRangeException".
My.Computer.FileSystem.RenameFile(Files(counter), TextBox1.Text & counter)
Next
End Sub
Files(counter) represents the file that it's currently at. If counter = 0 then Files(counter) would be the first file path in the array, and so on.
One thing I don't understand is why you give the new files the name of whatever you put in TextBox1 and an x. You are currently giving every file in that directory the exact same name (which is impossible). Could you tell me what you really are trying to rename them to?
In the mean time I replaced the x with counter. That will rename them to <whatever is in TextBox1>0, <whatever is in TextBox1>1, and so on.
One last thing, as you might have noticed I put the ampersand (&) instead of the plus sign (+) in the second parameter of RenameFile. Using the ampersand is the recommended way of concatenating strings, as the plus sign could cause exceptions in certain cases.
EDIT:
To keep the extension of the file you just have to extract it, and then add it to the new name:
For counter As Integer = 0 To Files.Length - 1
Dim FileExtension As String = Path.GetExtension(Files(counter)) 'Keeping the extension.
My.Computer.FileSystem.RenameFile(Files(counter), TextBox1.Text & counter & FileExtension)
Next

GetDirectory will not list all Directories

I have a form that allows you to click a button, which triggers an OpenFileDialog. From there, you are suppose to select a specific file within that folder, and then the program is supposed to go through from the folder you were in the the /subjects folder and list those directories.
At the moment, I have 3 directories within /subjects: english, mathematics, and cte.
My issue is that when the program is ran, it will only list the English directory in the combo-box, and will not list any of the others.
Private Sub btnDocumentChoice_Click(sender As Object, e As EventArgs) Handles btnDocumentChoice.Click
Dim ofd As New OpenFileDialog
Dim DirList As New ArrayList
If ofd.ShowDialog = Windows.Forms.DialogResult.OK AndAlso ofd.FileName <> "" Then
strRootLocation = (Path.GetDirectoryName(ofd.FileName))
GetDirectories(strRootLocation + "/subject/", DirList)
'MessageBox.Show(Path.GetDirectoryName(ofd.FileName))
End If
End Sub
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
strRootLocation = OpenFileDialog1.FileName
cmbSubject.Items.Add(strRootLocation)
End Sub
Sub GetDirectories(ByVal StartPath As String, ByRef DirectoryList As ArrayList)
Dim Dirs() As String = Directory.GetDirectories(StartPath)
DirectoryList.AddRange(Dirs)
For Each Dir As String In Dirs
GetDirectories(Dir, DirectoryList)
cmbSubject.Items.Add(Replace(Path.GetDirectoryName(Dir), strRootLocation + "\subject", ""))
cmbSubject.Items.Remove("")
Next
End Sub
I managed to fix my own issue by removing the For Each loop in the question, and replacing it with this:
Dim directories As String
For Each directories In Directory.GetDirectories(strRootLocation + "\subject")
cmbSubject.Items.Add(Replace(directories, strRootLocation + "\subject\", ""))
Next

Opening listview items with a double click vb.net

I want to open items from a list view with a double click.
Imports System.IO
Imports System.Xml
Public Class cv7import
Private Sub cv7import_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim caminho As String
caminho = "C:\Documents and Settings\Software\Ambiente de trabalho\cv7import"
lstvicon.View = View.Details
lstvicon.GridLines = False
lstvicon.FullRowSelect = True
lstvicon.HideSelection = False
lstvicon.MultiSelect = True
lstvicon.Columns.Add("Nome")
lstvicon.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize)
Dim DI As System.IO.DirectoryInfo = New System.IO.DirectoryInfo(caminho)
Dim files() As System.IO.FileInfo = DI.GetFiles
Dim file As System.IO.FileInfo
Dim li As ListViewItem
For Each file In files
li = lstvicon.Items.Add(file.Name)
Next
End Sub
Private Sub btnimp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnimp.Click
Dim caminho As String
caminho = "C:\Documents and Settings\Software\Ambiente de trabalho\cv7import"
Dim items() As ListViewItem = lstvicon.SelectedItems.Cast(Of ListViewItem).ToArray
Dim csv() As String = Array.ConvertAll(items, Function(lvi) String.Join(",", lvi.SubItems.Cast(Of ListViewItem.ListViewSubItem).Select(Function(si) si.Text).ToArray))
IO.File.WriteAllLines("C:\Documents and Settings\Software\Ambiente de trabalho\cv7import\teste.csv", csv)
End Class
That's the important part of the code, I was think of using onclick but I cant seem to get anywhere with it, any suggestions?
I also considered using and Open File Dialog but I dont think it can be done without the user's input of a path
I'm assuming that when you say open, you mean you want to open the associated file in the default program for that file type. In that case, you need to be storing the full path to the file in the list view. That can be accomplished via this code:
For Each file In files
li = lstvicon.Items.Add(file.Name)
li.Tag = file.FullName
Next
You will then need to add an event for the listview's double-click method. Within that event you'll want to look at the selected item and run the default program for it.
Private Sub lstvicon_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstvicon.DoubleClick
Process.Start(lstvicon.SelectedItems(0).Tag)
End Sub