How to remove path in my search code on vb.net - vb.net

I am very new to VB and I have an assignment which requires me to have search code in the program.The search code works but it shows the path of the file and I just want it to show the name of the txt file.
Private Sub SearchOrdersToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SearchOrdersToolStripMenuItem.Click
txtSearch.Visible = True
Lblsearch.Visible = True
Dim backslash As String() = FrmLogIn.FolderDirectory.Split("\")
Dim filename As String = backslash(6)
ListOfAllFileNames = System.IO.Directory.GetFiles(FrmLogIn.FolderDirectory)
TxtShoworders.Lines = ListOfAllFileNames
End Sub
Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
If txtSearch.Text = "" Then
TxtShoworders.Lines = ListOfAllFileNames
Return
Else
Dim SearchResults As New List(Of String)
For Each currentFileName In ListOfAllFileNames
If currentFileName.Contains(txtSearch.Text) Then
SearchResults.Add(currentFileName)
End If
Next
TxtShoworders.Lines = SearchResults.ToArray()
End If
End Sub
Link to what the program looks like and the directory showing
If anyone could help me with this that would be great, thanks.

You'll have to use Path.GetFileName for this, example:
SearchResults.Add(Path.GetFileName(currentFileName))
To keep your list of paths but only show the filenames, try this:
Private Sub SearchOrdersToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SearchOrdersToolStripMenuItem.Click
txtSearch.Visible = True
Lblsearch.Visible = True
Dim backslash As String() = FrmLogIn.FolderDirectory.Split("\")
Dim filename As String = backslash(6)
ListOfAllFileNames = System.IO.Directory.GetFiles(FrmLogIn.FolderDirectory)
TxtShoworders.Lines = GetFileNames(ListOfAllFileNames)
End Sub
Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
If txtSearch.Text = "" Then
TxtShoworders.Lines = GetFileNames(ListOfAllFileNames)
Return
Else
Dim SearchResults As New List(Of String)
For Each currentFileName In ListOfAllFileNames
If currentFileName.Contains(txtSearch.Text) Then
SearchResults.Add(currentFileName)
End If
Next
TxtShoworders.Lines = GetFileNames(SearchResults.ToArray())
End If
End Sub
Private Function GetFileNames(Byval paths as String()) As String()
Return paths.Select(Function(p) Path.GetFileName(p)).ToArray()
End Function
This will keep your ListOfAllFileNames containing the paths while only showing the file names using GetFileNames.

Related

Copy a File Using DragDrop VB.Net

What is wrong with my code? Getting a 'Process cannot access the file because it is being used by another process' error msg Is there a way around this. My google-fu was not giving me much luck. I was not able to Move or Copy, and I will take either.
Private Sub frmFiberTransMain_DragEnter(sender As Object, e As DragEventArgs) Handles MyBase.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop, False) = True Then
e.Effect = DragDropEffects.All
End If
End Sub
Private Sub frmFiberTransMain_DragDrop(sender As Object, e As DragEventArgs) Handles MyBase.DragDrop
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
Dim filePaths As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
Call CopyFileDrop(filePaths)
End If
End Sub
Private Sub CopyFileDrop(filePaths As String())
For Each fileLoc As String In filePaths
Dim fileName As String = fileLoc
Dim fi As New IO.FileInfo(fileName)
File.Create(fileName)
Dim justFileName As String = fi.Name
Dim newPathName As String = gProgDir & "\" & justFileName
Directory.Move(fileLoc, newPathName)
Next fileLoc
End Sub
File.Create(fileName) returns an open handle and you're not closing it. It doesn't look like you need that line. –
#LarsTech 50 mins ago

Remove duplicate characters from strings and find the shortest

I can not figure out how to select from the result or the shortest line itself or its number
(Yes, the solution is needed in such ancient operators)
Imports System.IO
Public Class Form1
Sub readputh(ByRef s As String)
s = ""
OpenFileDialog1.Filter = "Textfiles (*.txt)|*.txt"
OpenFileDialog1.ShowDialog()
Do While s = ""
s = OpenFileDialog1.FileName
Loop
End Sub
Sub writeputh(ByRef s As String)
s = ""
SaveFileDialog1.Filter = "Textfiles (*.txt)|*.txt"
SaveFileDialog1.ShowDialog()
Do While s = ""
s = SaveFileDialog1.FileName
Loop
End Sub
Sub ch(ByVal Str As String, ByRef Res As String)
Dim a As Char
Res = Mid(Str, 1, 1)
For i = 2 To Len(Str)
a = CChar(Mid(Str, i, 1))
If InStr(Res, a) = 0 Then
Res = Res + a
End If
Next
End Sub
Sub resh(ByVal filename1 As String, ByVal filename2 As String, ByRef lb1 As ListBox, ByRef lb2 As ListBox)
Dim rf As StreamReader
Dim wf As StreamWriter
Dim s1, s2, s3 As String
s2 = ""
s3 = ""
Try
rf = New StreamReader(filename1)
wf = New StreamWriter(filename2, True)
Do While Not rf.EndOfStream()
s1 = rf.ReadLine()
lb1.Items.Add(s1)
ch(s1, s2)
wf.WriteLine(s2)
lb2.Items.Add(s2)
Loop
wf.Close()
rf.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim filename1, filename2 As String
readputh(filename1)
writeputh(filename2)
resh(filename1, filename2, ListBox1, ListBox2)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
End
End Sub
End Class
Input file:
youtubeyoutubeyotube
dogdogdogdog
geeksforgeeks
Output file:
youtbe
dog
geksfor
But I expect Output file of only "dog"
I just couldn't handle the old code. One based functions? No! You can translate it back it you want but output is now dog.
Private Function GetOpenPath() As String
OpenFileDialog1.Filter = "Textfiles (*.txt)|*.txt"
If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Return OpenFileDialog1.FileName
Else
Return Nothing
End If
End Function
Private Function GetSavePath() As String
SaveFileDialog1.Filter = "Textfiles (*.txt)|*.txt"
If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Return SaveFileDialog1.FileName
Else
Return Nothing
End If
End Function
Private Function ch(ByVal Str As String) As String
Dim a As Char
Dim Res = Str.Substring(0, 1)
For i = 1 To Str.Length - 1
a = CChar(Str.Substring(i, 1))
If Res.IndexOf(a) = -1 Then
Res &= a
End If
Next
Return Res
End Function
Sub resh(ByVal filename1 As String, ByVal filename2 As String)
Dim lines = File.ReadAllLines(filename1)
Dim NewLines As New List(Of String)
For Each line In lines
Try
ListBox1.Items.Add(line)
Dim s2 = ch(line)
NewLines.Add(s2)
ListBox2.Items.Add(s2)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
Dim Shortest = NewLines.OrderByDescending(Function(s) s.Length).Last()
File.WriteAllText(filename2, Shortest)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim OpenPath = GetOpenPath()
Dim SavePath = GetSavePath()
If String.IsNullOrEmpty(OpenPath) OrElse String.IsNullOrEmpty(SavePath) Then
MessageBox.Show("You must provide a file. Try again.")
Return
End If
resh(OpenPath, SavePath)
End Sub

hide folder name in tree list

how do i hide specific name folder within the treelist ? i have tree list like this
and i want to hide folder name New folder and pdf. i make this from Load Data Dir. i have tweak a bit in the code like this by putting if
Dim rootfolder As String = "C:\\FFOutput"
Private Sub TreeList1_VirtualTreeGetCellValue(ByVal sender As Object, ByVal e As DevExpress.XtraTreeList.VirtualTreeGetCellValueInfo) Handles TreeList1.VirtualTreeGetCellValue
Dim di As New DirectoryInfo(CStr(e.Node))
If di.Name <> "New folder" Then
If e.Column Is TreeListColumn1 Then
e.CellData = di.Name
End If
If e.Column Is TreeListColumn2 Then
e.CellData = e.Node.ToString
End If
If e.Column Is TreeListColumn3 Then
If IsFile(di) Then
e.CellData = New FileInfo(CStr(e.Node)).Extension
Else
e.CellData = Nothing
End If
End If
End If
End Sub
Private Sub TreeList1_VirtualTreeGetChildNodes(ByVal sender As Object,
ByVal e As DevExpress.XtraTreeList.VirtualTreeGetChildNodesInfo) _
Handles TreeList1.VirtualTreeGetChildNodes
If loadDrives = False Then
Dim root As String() = Directory.GetDirectories(rootfolder)
e.Children = root
loadDrives = True
Else
Try
Dim di As New DirectoryInfo(CStr(e.Node))
If di.Name <> "New folder" Then
Dim path As String = CStr(e.Node)
If Directory.Exists(path) Then
Dim dirs As String() = Directory.GetDirectories(path)
Dim files As String() = Directory.GetFiles(path)
Dim arr(dirs.Length + files.Length) As String
dirs.CopyTo(arr, 0)
files.CopyTo(arr, dirs.Length)
e.Children = arr
Else
e.Children = New Object() {}
End If
End If
Catch
End Try
End If
End Sub
and it become like this

ProgressBar not updating using a For Each loop

I'm copying all the .avi and .png files from one folder into another:
Private Sub CopierSend_Button_Click(sender As Object, e As EventArgs) Handles CopierSend_Button.Click
If MessageBox.Show("Click OK to send media or just Cancel.", "Media Copier", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
For Each foundFile As String In My.Computer.FileSystem.GetFiles(FrapsFolder_, Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.avi", "*.png")
Dim foundFileInfo As New System.IO.FileInfo(foundFile)
My.Computer.FileSystem.CopyFile(foundFile, DestFolder_ & foundFileInfo.Name, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
Next
Else
'Nothing Yet
End If
End Sub
I want to add a ProgressBar which will count every time a file is copied, so I added this code before the For Each loop:
Dim file1() As String = IO.Directory.GetFiles(FrapsFolder_, "*.avi")
Dim file2() As String = IO.Directory.GetFiles(FrapsFolder_, "*.png")
Dim files = file1.Length + file2.Length
Copier_ProgressBar.Step = 1
Copier_ProgressBar.Maximum = files
And added this code inside the For Each loop:
Copier_ProgressBar.Value += 1
Here is all of my code:
Private Sub CopierSend_Button_Click(sender As Object, e As EventArgs) Handles CopierSend_Button.Click
If MessageBox.Show("Click OK to send media or just Cancel.", "Media Copier", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
Dim file1() As String = IO.Directory.GetFiles(FrapsFolder_, "*.avi")
Dim file2() As String = IO.Directory.GetFiles(FrapsFolder_, "*.png")
Dim files = file1.Length + file2.Length
Copier_ProgressBar.Step = 1
Copier_ProgressBar.Maximum = files
For Each foundFile As String In My.Computer.FileSystem.GetFiles(FrapsFolder_, Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.avi", "*.png")
Dim foundFileInfo As New System.IO.FileInfo(foundFile)
My.Computer.FileSystem.CopyFile(foundFile, DestFolder_ & foundFileInfo.Name, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
Copier_ProgressBar.Value += 1
Next
Else
'Nothing Yet
End If
End Sub
The ProgressBar updates, but only after all the files have been copied instead of updating in real time. Any idea?
As it stands it looks like the ProgressBar doesn't do anything until after all the files have copied. That isn't strictly true. Instead your UI is not updating.
Instead you should look into using a BackgroundWoker to report progress. Something like this should do the trick:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'This can also be set using the Designer
BackgroundWorker1.WorkerReportsProgress = True
End Sub
Private Sub CopierSend_Button_Click(sender As Object, e As EventArgs) Handles CopierSend_Button.Click
If MessageBox.Show("Click OK to send media or just Cancel.", "Media Copier", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
Dim file1() As String = IO.Directory.GetFiles(FrapsFolder_, "*.avi")
Dim file2() As String = IO.Directory.GetFiles(FrapsFolder_, "*.png")
Dim files As Integer = file1.Length + file2.Length
Copier_ProgressBar.Step = 1
Copier_ProgressBar.Maximum = files
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
For Each foundFile As String In My.Computer.FileSystem.GetFiles(FrapsFolder_, Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.avi", "*.png")
Dim foundFileInfo As New System.IO.FileInfo(foundFile)
My.Computer.FileSystem.CopyFile(foundFile, DestFolder_ & foundFileInfo.Name, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
BackgroundWorker1.ReportProgress(Copier_ProgressBar.Value + 1)
Next
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Copier_ProgressBar.Value = e.ProgressPercentage
End Sub
As an additional note, for best practice, I would consider using Path.Combine instead of concatenating strings together:
My.Computer.FileSystem.CopyFile(foundFile, Path.Combine(DestFolder_, foundFileInfo.Name), Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)

Save clicks to file

I got asked a couple of days ago how to save number of clicks you have done to each button in a program to a small file, to keep track of what is most used. Since it was ages ago i dabbled with visual basic i said i would raise the question here, so here goes.
There are 5 buttons labels Button1-Button5. When a button is clicked it should look for the correct value in a file.txt and add +1 to the value. The file is structured like this.
Button1 = 0
Button2 = 0
Button3 = 0
Button4 = 0
Button5 = 0
So when button1 is clicked it should open file.txt, look for the line containing Button1 and add +1 to the value and close the file.
I have tried looking for some kind of tutorial on this but have not found it so i'm asking the collective of brains here on Stackoverflow for some guidance.
Thanks in advance.
delete file first
new ver ..
Imports System.IO.File
Imports System.IO.Path
Imports System.IO
Imports System.Text
Public Class Form1
Dim line() As String
Dim strbild As StringBuilder
Dim arr() As String
Dim i As Integer
Dim pathAndFile As String
Dim addLine As System.IO.StreamWriter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim fileName As String = "myfile.txt"
Dim appPath As String = My.Application.Info.DirectoryPath
pathAndFile = Path.Combine(appPath, fileName)
If System.IO.File.Exists(pathAndFile) Then
'line = File.ReadAllLines(pathAndFile)
Else
Dim addLineToFile = System.IO.File.CreateText(pathAndFile) 'Create an empty txt file
Dim countButtons As Integer = 5 'add lines with your desired number of buttons
For i = 1 To countButtons
addLineToFile.Write("Button" & i & " = 0" & vbNewLine)
Next
addLineToFile.Dispose() ' and close file
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
writeToFile(1)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
writeToFile(2)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
writeToFile(3)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
writeToFile(4)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
writeToFile(5)
End Sub
Public Sub writeToFile(buttonId As Integer)
Dim tmpButton As String = "Button" & buttonId
strbild = New StringBuilder
line = File.ReadAllLines(pathAndFile)
Dim f As Integer = 0
For Each lineToedit As String In line
If InStr(1, lineToedit, tmpButton) > 0 Then
Dim lineSplited = lineToedit.Split
Dim cnt As Integer = lineSplited.Count
Dim newVal = addCount(CInt(lineSplited.Last()))
lineSplited(cnt - 1) = newVal
lineToedit = String.Join(" ", lineSplited)
line(f) = lineToedit
End If
f = f + 1
Next
strbild = New StringBuilder
'putting together all the reversed word
For j = 0 To line.GetUpperBound(0)
strbild.Append(line(j))
strbild.Append(vbNewLine)
Next
' writing to original file
File.WriteAllText(pathAndFile, strbild.ToString())
Me.Refresh()
End Sub
' Reverse Function
Public Function ReverseString(ByRef strToReverse As String) As String
Dim result As String = ""
For i As Integer = 0 To strToReverse.Length - 1
result += strToReverse(strToReverse.Length - 1 - i)
Next
Return result
End Function
Public Function addCount(ByVal arr As Integer) As Integer
Return arr + 1
End Function
End Class
Output in myfile.txt
Button1 = 9
Button2 = 2
Button3 = 4
Button4 = 0
Button5 = 20
Create a vb winform Application
Drag on your form 5 buttons (Button1, Button2, ... etc)
copy that :
Imports System.IO.File
Imports System.IO.Path
Imports System.IO
Imports System.Text
Public Class Form1
Dim line() As String
Dim strbild As StringBuilder
Dim arr() As String
Dim i As Integer
Dim pathAndFile As String
Dim addLine As System.IO.StreamWriter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim fileName As String = "myfile.txt"
Dim appPath As String = My.Application.Info.DirectoryPath
pathAndFile = Path.Combine(appPath, fileName)
If System.IO.File.Exists(pathAndFile) Then
line = File.ReadAllLines(pathAndFile)
Else
Dim addLineToFile = System.IO.File.CreateText(pathAndFile) 'Create an empty txt file
Dim countButtons As Integer = 5 'add lines with your desired number of buttons
For i = 1 To countButtons
addLineToFile.Write("Button" & i & " = 0" & vbNewLine)
Next
addLineToFile.Dispose() ' and close file
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
writeToFile(1)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
writeToFile(2)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
writeToFile(3)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
writeToFile(4)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
writeToFile(5)
End Sub
Public Sub writeToFile(buttonId As Integer)
Dim tmpButton As String = "Button" & buttonId
strbild = New StringBuilder
line = File.ReadAllLines(pathAndFile)
i = 0
For Each lineToedit As String In line
If lineToedit.Contains(tmpButton) Then
Dim lineSplited = lineToedit.Split
Dim newVal = addCount(CInt(lineSplited.Last()))
'lineToedit.Replace(lineSplited.Last, newVal)
lineToedit = lineToedit.Replace(lineToedit.Last, newVal)
line(i) = lineToedit
End If
i = i + 1
Next
strbild = New StringBuilder
'putting together all the reversed word
For j = 0 To line.GetUpperBound(0)
strbild.Append(line(j))
strbild.Append(vbNewLine)
Next
' writing to original file
File.WriteAllText(pathAndFile, strbild.ToString())
End Sub
' Reverse Function
Public Function ReverseString(ByRef strToReverse As String) As String
Dim result As String = ""
For i As Integer = 0 To strToReverse.Length - 1
result += strToReverse(strToReverse.Length - 1 - i)
Next
Return result
End Function
Public Function addCount(ByVal arr As Integer) As Integer
Return arr + 1
End Function
End Class
Have fun ! :)CristiC777
try this on vs2013
change If confition
line = File.ReadAllLines(pathAndFile)
i = 0
For Each lineToedit As String In line
If InStr(1, lineToedit, tmpButton) > 0 Then
'If lineToedit.Contains(tmpButton) = True Then
Dim lineSplited = lineToedit.Split
Dim newVal = addCount(CInt(lineSplited.Last()))
lineToedit = lineToedit.Replace(lineToedit.Last, newVal)
line(i) = lineToedit
End If
i = i + 1
Next