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

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

Related

how to get the accessible folder names from a drive with vb.net (Visual Studio 2012 Express)

I am trying to create a program for a friend that allows him to "sort out" and locate his files.
He has a couple of drives and many folders. What I would like to do for him is:
Have code that lists all of the active drives in a combo box. He can then select which drive he wants to search for any or just selected file types by extension.
Then he either selects "Everything" or a specific type (ie: Music)
Once a button is clicked, a list box fills with the full path to the file
Beginning this writing process, I have accomplished this:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Button1.Enabled = False
Dim allDrives() As DriveInfo = DriveInfo.GetDrives()
Dim d As DriveInfo
For Each d In allDrives
If d.IsReady Then ComboBox1.Items.Add(d)
Next
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If ComboBox1.SelectedIndex <> -1 Then
Try
For Each DName As String In My.Computer.FileSystem.GetDirectories(ComboBox1.Text, FileIO.SearchOption.SearchTopLevelOnly)
Dim LDN As Integer = Len(DName)
Dim FName As String = Strings.Mid(DName, 4, LDN - 3)
CheckedListBox1.Items.Add(FName, False)
Next
Catch ex As Exception
End Try
Else
Exit Sub
End If
End Sub
My first problem is that the GetDirectories process is getting directories I know that I do not have access to. I am trying to figure out how to prevent this. Can anyone help me.

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

VB.NET How to copy the application's executable file to another path?

I'm new to VB.NET and I'm trying to experiment with it. So when the user clicks a button from the application, the executable file should copy itself to a specific path.
So, how can I do that?
Thanks.
This is not recommended but possible - think about why in the earth you want to do that. A software is not just an EXE.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FileToCopy As String
Dim NewCopy As String
FileToCopy = Application.StartupPath.ToString & "\WindowsApplication1.exe"
NewCopy = "D:\_working\WindowsApplication1.exe.copied"
If System.IO.File.Exists(FileToCopy) = True Then
System.IO.File.Copy(FileToCopy, NewCopy)
MessageBox.Show("File Copied")
End If
End Sub
End Class
The code above is flawed if you are speaking about getting your own assembly in Visual Studios to copy itself to a given path. I tested the following code and it worked without error. Please note the path will have to be changed to fit your needs and be sure to use the name of your program, mine was CryLok.exe.
Reference: https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.location?view=net-5.0
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim FileToCopy As String
Dim NewCopy As String
FileToCopy = Reflection.Assembly.GetExecutingAssembly().Location
NewCopy = "C:\Users\your name\Desktop\CryLok.exe"
If File.Exists(FileToCopy) = True Then
File.Copy(FileToCopy, NewCopy)
MessageBox.Show("File Copied")
End If
End Sub

Go upper folder/directory 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)

For Each Item in ListBox1 do something then add item to listbox2 vb

I made an app to convert certain numbers to other format
i.e
1 = A
2 = B
3 = C
4 = D
5 = E
ETC
I have made that function with no problem and I have been using it for quite sometime, but now I would like to do things faster and in a batch.
So it's really difficult for me to copy from a text file to my Textbox1 then press button1 then copy textbox2 to other text file.
So I was thinking in loading the text file into a List Box then do a loop for each item in that list into a second list that I can export to another text file.
The importing and exporting I have it covered but where I'm stuck at is to make the loop.
Here's what I have please if you know a better way to do it let me know or tell me how to fix it this way.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using FD As New OpenFileDialog()
FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
ListBox1.Items.Clear()
ListBox1.Items.AddRange(IO.File.ReadAllLines(FD.FileName))
End If
End Using
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Do
Dim Item As String = ""
For Each i As String In ListBox1.Items
Item &= i
TextBox1.Text = Item
TextBox2.Text = MYFUNCTION(TextBox1.Text)
ListBox2.Items.Add(TextBox2.Text)
TextBox1.Text = ""
TextBox2.Text = ""
Next
Loop Until TextBox1.Text = "END"
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
'TextBox2.Text = MeidHexToDec(TextBox1.Text)
Using FD As New SaveFileDialog()
FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim FileContent As String = ""
For Each i As String In ListBox2.Items
FileContent &= i & vbCrLf
Next
IO.File.WriteAllText(FD.FileName, FileContent)
End If
End Using
End Sub
So my final aim is to do something like this:
TextFile1.txt
1
2
5
5
1
3
2
END
then after the conversion output
TextFile2.txt
A
B
E
E
A
C
B
The text file size will vary sometimes it will have only 10 items sometimes will be 50...
Thanks.
You do not need the Do loop at all and you can simplify the rest of your loop logic, like this:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each i As String In ListBox1.Items
ListBox2.Items.Add(MYFUNCTION(i))
Next
End Sub
You do not need to look out for the END marker, because everything in the file was read into the ListBox1.Items collection, thus once you have looped through all of the string values in ListBox1.Items, then you are at the end of the file.
The MYFUNCTION logic returns the transformation from number to letter, thus just add the result of that function into ListBox2.Items and you are done.
Public Function Letr(N As Int16) As String
Letr = Chr(N + 64)
End Function