check if file contains item in list - vb.net

I have a list of graphic names, "graphicList". I need to search my file for each item in the graphicList in an entity string. I don't know how to reference each item in the graphicList and search for it.
Code so far:
Dim Regex = New Regex("<!ENTITY .*?SYSTEM ""<graphicListItem>"" .*?>")
Dim strMasterDoc = File.ReadAllText(FileLocation)
Dim rxMatches = Regex.Matches(strMasterDoc)
Dim entityList As New List(Of String)
Dim entityFound As MatchCollection = Regex.Matches(strMasterDoc)
'For each file's multipled image file references
For Each m As Match In entityFound
Dim found As Group = m.Groups(1)
entityList.Add(found.Value)
Next

I found the answer to my question
For Each item As Match In graphicRefList
Dim found As Group = item.Groups(1)
GraphicList.Add(found.Value)
Dim Regex = New Regex("(<!ENTITY " & found.Value & " SYSTEM ""\w.+?\w"" .*?>)")
Next

Related

get full string before first second third etc. split

I have a file location and I need to check if it exists.
The way I wan't to do it is like this:
Dim route As String = ("C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt")
If System.IO.File.Exists(route) Then
MsgBox("BESTAAT HET WERKT!")
Else
Dim subroute() As String = route.Split("\"c)
Dim counting As Integer = route.Split("\"c).Length - 1
For count2 As Integer = 0 To counting - 1
Dim firstbackslash As Integer = route.IndexOf("\")
Dim backslash As Integer = route.IndexOf("\", firstbackslash + 1)
Dim firstPart As String = route.Substring(0, backslash)
MsgBox(firstPart)
Next
What I try to accomplisch is that I fist check if folder "C:" exists then "C:\testing1" then "C:\testing1\testing2" etc.
But I cant find something like this on the internet nor with some messing around...
Here is an algorithm that that will give you all the paths starting from the root and building up to the final path including the filename. You can use this to check for each folder and create them as you go if they don't exist:
Sub Main()
Dim route As String = ("C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt")
Dim fi As New System.IO.FileInfo(route)
If Not fi.Exists Then
Dim fileName As String = Path.GetFileName(route)
Dim di As DirectoryInfo = fi.Directory
Dim pathStack As New Stack(Of String)()
pathStack.Push(di.Name)
While Not IsNothing(di.Parent)
di = di.Parent
pathStack.Push(di.Name)
End While
Dim curPath As String = ""
While pathStack.Count > 0
curPath = Path.Combine(curPath, pathStack.Pop)
' ... do something with "curPath" in here ...
' ... like check for existence and create it ...
Console.WriteLine(curPath)
End While
curPath = Path.Combine(curPath, fileName)
' ... do something with "curPath" in here ...
' ... this is the full path including the file on the end ...
Console.WriteLine(curPath)
End If
Console.Write("Press Enter to quit...")
Console.ReadLine()
End Sub
Output:
C:\
C:\testing1
C:\testing1\testing2
C:\testing1\testing2\testing3
C:\testing1\testing2\testing3\testing4
C:\testing1\testing2\testing3\testing4\testing5
C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt
Press Enter to quit...
Don't use string mnaipulation to work with file or folder paths. use the Path class.
One option:
Private Function GetExistingSubPath(fullPath As String) As String
If Directory.Exists(fullPath) OrElse File.Exists(fullPath) Then
Return fullPath
End If
Dim subPath = Path.GetDirectoryName(fullPath)
If subPath Is Nothing Then
Return Nothing
End If
Return GetExistingSubPath(subPath)
End Function
Sample usage:
Dim fullPath = "C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt"
Dim existingSubPath = GetExistingSubPath(fullPath)
Console.WriteLine(existingSubPath)
What I try to accomplisch is that I fist check if folder "C:" exists then "C:\testing1" then "C:\testing1\testing2" etc.
Noooooooooooo!
That's not how to do it at all! The file system is volatile: things can change between each of those checks. Moreover, file existence is only one of many things that can stop file access.
It's much better practice to try to access the file in question, and then handle the exception if it fails. Remember, because of the prior paragraph you have to be able to handle exceptions here anyway. .Exists() doesn't save you from writing that code. And each check is another round of disk access, which is about the slowest thing it's possible to do in a computer... even slower than unrolling the stack for an exception, which is the usual objection to this idea.
I fixed it, know I can check if multiple text files are at the locations I need, if there not I place the Textfiles at the location I need them. Then I can add something in it. (I need to put a Location of something else in it.)
Dim een As String = "C:\testing1\testing2\testing7\testing1\testing1\text.txt"
Dim twee As String = "C:\testing1\testing2\testing7\testing2\testing1\text.txt"
Dim drie As String = "C:\testing1\testing2\testing7\testing3\testing1\text.txt"
Dim vier As String = "C:\testing1\testing2\testing7\testing4\testing1\text.txt"
Dim Files As String() = {een, twee, drie, vier}
For Each route As String In Files
If System.IO.File.Exists(route) Then
MsgBox("BESTAAT HET WERKT!")
Else
Dim subroute() As String = route.Split("\"c)
Dim counting As Integer = route.Split("\"c).Length - 1
Dim tel As Integer = route.Substring(route.LastIndexOf("\") + 1).Count
Dim bestandnaam As String = route.Substring(route.LastIndexOf("\") + 1)
For count2 As Integer = 0 To route.Length - tel - 1
Dim firstbackslash As Integer = route.IndexOf("\", count2)
Dim backslash As Integer = route.IndexOf("\", count2)
Dim Mapnaam As String = route.Substring(0, backslash)
count2 = firstbackslash
If System.IO.Directory.Exists(Mapnaam) Then
Else
System.IO.Directory.CreateDirectory(Mapnaam)
End If
Next
If System.IO.File.Exists(route) Then
Else
Dim objStreamWriter As System.IO.StreamWriter
objStreamWriter = New System.IO.StreamWriter(route)
Dim label As String
Select Case route
Case een
label = "een"
Case twee
label = "twee"
Case drie
label = "drie"
Case vier
label = "vier"
End Select
Dim value As String = InputBox("Route invullen naar " & label)
'Dim objStreamWriter As New System.IO.StreamWriter(route)
objStreamWriter.Write(value)
objStreamWriter.Close()
'Using sw As System.IO.StreamWriter = System.IO.File.AppendText(route)
' sw.WriteLine(value)
'End Using
End If
End If
Next route

vb- How to assign a different tag property to different array words?

This is my code for inserting from textfile to array to labels, but I want to be able to assign a tag property onto some of the words or perhaps use the 'Answer' which is located a line below on my text file??
IndexNo = 0
Dim FileTerm As String = "D:\soccer.txt"
Dim FileNum As Integer = FreeFile()
FileOpen(FileNum, FileTerm, OpenMode.Input)
Do
Term(IndexNo) = LineInput(FileNum)
Answer(IndexNo) = LineInput(FileNum)
IndexNo = IndexNo + 1
Loop Until EOF(FileNum)
FileClose(FileNum)
Dim Obj As Object, Count As Integer = 0
For Each Obj In Me.Controls
If TypeOf Obj Is Label Then
MyLabels(Count) = Obj
Count = Count + 1
End If
Next
Dim Random1, Random2 As Integer
Dim TempTerm, TempAnswer As Object
For Count = 0 To 15
Randomize()
Random1 = Val(Int(16 * Rnd()))
Random2 = Val(Int(16 * Rnd()))
TempTerm = Term(Random1)
Term(Random1) = Term(Random2)
Term(Random2) = TempTerm
TempAnswer = Answer(Random1)
Answer(Random1) = Answer(Random2)
Answer(Random2) = TempAnswer
Count = Count + 1
Next
For Count = 0 To 15
MyLabels(Count).Text = Term(Count)
Next
If anyone has any ideas, the help is appreciated. Thanks
Even though your question is not very clear. From what I get, you want to have some way to keep your Labels and the corresponding Term and Answers in sync.
There are many ways to do this, but I would prefer to do it as below... the perfect VB.NET way as opposed to using any legacy VB6 techniques.
First declare a class that would keep our Term and Answers in one object. This is the equivalent of Type in VB6.
Public Class TermAnswer
Public Term As String
Public Answer As String
' you may add more fields/properties here if you wish to...
End Class
Now it is easy to code our solution.
' declare a Dictionary object with Label as key and the corresponding Term and Answers as values.
Dim TermAnswers As New Dictionary(Of Label, TermAnswer)
' this is a temporary List to hold our Term and Answers read from file until we randomize them.
Dim tempTermAnswers As New List(Of TermAnswer)
' Our Labels array... yes it is this easy :)
Dim myLabels() As Label = Me.Controls.OfType(Of Label)().ToArray
' read our file into the tempTermAnswers List
Dim FileTerm As String = "D:\soccer.txt"
Using reader As New IO.StreamReader(FileTerm)
While Not reader.EndOfStream
Dim ta As New TermAnswer
ta.Term = reader.ReadLine
ta.Answer = reader.ReadLine
tempTermAnswers.Add(ta)
End While
reader.Close()
End Using
' pick Term Answers from our tempTermAnswers List randomly and add them to our TermAnswers Dictionary
' we also set our Label text here, though you can loop separately too
Dim randomNumbers As New Random
Dim tempTerm As TermAnswer, randomNumber As Integer
For Each label In myLabels
randomNumber = randomNumbers.Next(0, tempTermAnswers.Count)
tempTerm = tempTermAnswers(randomNumber)
TermAnswers.Add(label, tempTerm)
tempTermAnswers.Remove(tempTerm)
label.Text = tempTerm.Term
Next
' now you have your term answers in a Dictionary, indexed by Label.
' you can get any of them by providing a Label on your form as key and get the corresponding Term and Answer as value.
' e.g. let us list the Label Name, Term and Answer in our debug window...
For Each label In myLabels
Debug.WriteLine(label.Name & " ... " & TermAnswers(label).Term & " ... " & TermAnswers(label).Answer)
Next

Renaming files listed within a listbox

I'm trying to create a little program thats able to alter the names of shotcuts, from a listbox-index.
I've created a button wich list every file with the targeted "extension"(targeted with combobox1), from where I want another button to be able to alter the files names:
Button 1 code(Searching for the files):
Dim kilde As New FolderBrowserDialog
If kilde.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim mappe = New System.IO.DirectoryInfo(kilde.SelectedPath)
txtbSti.Text = kilde.SelectedPath
End If
For Each f In Directory.GetFiles(txtbSti.Text, "*" & ComboBox1.Text & "*", SearchOption.AllDirectories)
If File.Exists(f) Then
With ListBox1
With .Items
.Add(f)
End With
End With
End If
Next f
This gives me a list with the desired files.
Is there a way, to rename the files, in my case,listed within listbox1, line by line?
Button 2 (not functioning)
For Each r As String In ListBox1.Items
System.IO.Path.ChangeExtension(ComboBox1.Text, " ")
Next r
You can use File.Move to "rename" a file:
System.IO.File.Move("oldfilename", "newfilename")
For example:
For Each oldFilePath As String In ListBox1.Items
If System.IO.File.Exists(oldFilePath) Then
Dim dir = System.IO.Path.GetDirectoryName(oldFilePath)
Dim newFilePath = System.IO.Path.Combine( dir, "newFileName")
System.IO.File.Move(oldFilePath, newFilePath)
End If
Next
Edit: In this case, remove the automatic generated extension ".avi - Shortcut"
If you just want to change an extension you can use Path.ChangeExtension:
System.IO.Path.ChangeExtension(oldFilePath, "new_extension")
Update: oh, sorry, it's a part of the name; the file is named, example; J:\Homemovies\Jumping around.avi - Shortcut.lnk, I want to remove the ".avi - Shortcut" part of the name on the actual file(s) listed within the listbox1 that is set up to find all the files within a targeted folder with that particular extension within it's name; J:\Homemovies\Jumping around.lnk
You can use String.Replace:
Dim name = System.IO.Path.GetFileName(oldFilePath).ToLowerInvariant()
Dim newName = name.Replace(".avi - shortcut.", ".")
Dim newPath = System.IO.Path.Combine(
System.IO.Path.GetDirectoryName(oldFilePath), newName)
Update2: still can't get either of those solutions to work
Here is a complete working sample:
First, read the shortcuts from your directory:
Dim dir = "C:\Temp\Homemovies"
For Each fn In Directory.EnumerateFileSystemEntries(dir, "*avi - shortcut*.*", SearchOption.AllDirectories)
ListBox1.Items.Add(fn)
Next
Second (in your button-click handler), rename those .Ink files by removing the part that contains(substring)"avi - shortcut", also handling the case that it already exists:
For Each fn As String In ListBox1.Items
If File.Exists(fn) Then
Dim folder = Path.GetDirectoryName(fn)
Dim fileName = Path.GetFileNameWithoutExtension(fn)
Dim extension = Path.GetExtension(fn)
Dim dotParts = fileName.Split("."c)
Dim allButAviShortCut = From part In dotParts
Where part.IndexOf("avi - shortcut", StringComparison.InvariantCultureIgnoreCase) = -1
Dim newFileName = String.Join(".", allButAviShortCut)
Dim newPath = System.IO.Path.Combine(dir, newFileName & extension)
Dim number = 0
While File.Exists(newPath)
' exists already, append number
number += 1
Dim newFileNameWithNum = String.Format("{0}_{1}", newFileName, number)
newPath = System.IO.Path.Combine(dir, newFileNameWithNum & extension)
End While
System.IO.File.Move(fn, newPath)
End If
Next
Consider the following:
ListBox1 contains list of all files in the selected directory.
txtbSti is the text box which holds the path to the selected directory.
Each file is renamed as New_fileX where X is the index of the file in the ListBox1
Now take a look into the code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer = 0
For Each r As String In ListBox1.Items
i += 1
My.Computer.FileSystem.RenameFile(txtbSti.Text & ":\" & r, "New_file" & i & ".txt")
Next r
End Sub

Adding records (Row/ Column) to DataGridView; Collection already belongs to a DataGridView control VB.NET

I'm looking for some help with an issue I am having.
I have multiple text files, in a folder. The folder can have an "unlimited" amount of text files in it, although typically 2-150 files
http://gyazo.com/5f314d1ca374abf9f813914609dd931d (images for this + below, can't embed due to lack of reputation)
Each file then contains an "unlimited" (although typically 0-20 lines) amount of data inside it. Line 1 being the "test number" and line 2 being the "test result" - as seen in the image above
My Data Grid View has 3 columns in it (Username, test number, test result) - as seen in the image above
When running my code below; first record being added to the Data Grid View works perfectly, but the second (or any record after the first) the error occurs:
http://gyazo.com/0d492b97d918853e62c55ee314f3f181 (image) or error message:
"System.InvalidOperationException: Collection already belongs to a
DataGridView control. This operation is no longer valid. at
System.Windows.Forms.DataGridViewCellCollection.Add(DataGridViewCelldataGridViewCell)
at SpellingBee.TeacherMultiResults.TeacherMultiResults_Load(Object
sender, EventArgs e)"
This error occurs on the DGVRow.Cells.Add(DGVCell) 'add cell to row
One thing I don't want to do is change any of my text file/ folder structures, even though I'm aware that it is currently inefficient storage.
How can I fix this error? I'm using VB.net (Visual Studios 2013)
If you need any more information, please just ask
Many thanks.
Imports System.Windows.Forms
Imports System.IO
Public Class TeacherMultiResults
Dim AmountOfFiles
Dim LineCount As Integer = 0
Dim FileName As IO.FileInfo
Dim DGVRow As New DataGridViewRow
Dim DGVCell As DataGridViewCell
Dim Username As String = ""
Dim TestNumber As Integer = 0
Dim TestResult As Integer = 0
Private Sub TeacherMultiResults_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim directory As New IO.DirectoryInfo(LoadForm.CurrentDirectory & "\UserResults\") 'selects directory
Dim FileNames As IO.FileInfo() = directory.GetFiles()
Dim Files As IO.FileInfo
For Each Files In FileNames 'list the names of all files in the specified directory
Username = Files.ToString
Username = (Username.Substring(0, Username.Length - 4)) 'removes the .txt from the name
Try
LineCount = File.ReadAllLines(LoadForm.CurrentDirectory & "\UserResults\" & Username & ".txt").Length 'amount of lines in file
If LineCount > 1 Then
Dim Information As New System.IO.StreamReader(LoadForm.CurrentDirectory & "\UserResults\" & Username & ".txt") 'opens file
LineCount = LineCount / 2 'halfs line count
For i = 0 To LineCount - 1
TestNumber = Information.ReadLine() 'reads line to variable
TestResult = Information.ReadLine() 'reads line to variable
i = i + 1 'adds one to i
DGVCell = New DataGridViewTextBoxCell 'create a new DGV text box cell
DGVCell.Value = Username 'add value to DGV text box cell
DGVRow.Cells.Add(DGVCell) 'add cell to row
DGVCell = New DataGridViewTextBoxCell 'create a new DGV text box cell
DGVCell.Value = TestNumber 'add value to DGV text box cell
DGVRow.Cells.Add(DGVCell) 'add cell to row
DGVCell = New DataGridViewTextBoxCell 'create a new DGV text box cell
DGVCell.Value = TestResult 'add value to DGV text box cell
DGVRow.Cells.Add(DGVCell) 'add cell to row
DGV_MultiResults.Rows.Add(DGVRow) 'add row to DGV
Next
Information.Close() 'Close read
End If
Catch ex As Exception 'if file won't read
MsgBox(ex.ToString) 'show error
Exit Try
End Try 'end of try
Next 'end of files
End Sub
I hope that somebody can help me with this issue, I understand it's fairly simple to fix most probably although I can't seem to find a solution to the error!
Many thanks, Toby.
When working with a DataGridView, it is generally easier to just build an object list and then bind it to the DGV using the built-in data binding features.
For your example, it would look like this:
' Read the files, build objects as you go and add them to a list
Dim lst = New List(Of TeacherMultiResults)
' Replace this part with your file reading code...
Dim t1 = New TeacherMultiResults With {.Username = "Bob", .TestNumber = 1, .TestResult = 75}
lst.Add(t1)
Dim t2 = New TeacherMultiResults With {.Username = "Rick", .TestNumber = 1, .TestResult = 85}
lst.Add(t2)
Dim t3 = New TeacherMultiResults With {.Username = "Zoe", .TestNumber = 1, .TestResult = 95}
lst.Add(t3)
' Bind the list to the DataGridView
Dim bindList = New BindingList(Of TeacherMultiResults)(lst)
Dim bindSrc = New BindingSource
bindSrc.DataSource = bindList
grid.DataSource = bindSrc
Your grid should display each item of your list.

Search line in text file and return value from a set starting point vb.net

I'm currently using the following to read the contents of all text files in a directory into an array
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
Within the text files are only 6 lines that all follow the same format and will read something like
forecolour=black
I'm trying to then search for the word "forecolour" and retrieve the information after the "=" sign (black) so i can then populate the below code
AllDetail(numfiles).uPath = ' this needs to be the above result
I've only posted parts of the code but if it helps i can post the rest. I just need a little guidance if possible
Thanks
This is the full code
Dim numfiles As Integer
ReDim AllDetail(0 To 0)
numfiles = 0
lb1.Items.Clear()
Dim lynxin As New IO.DirectoryInfo(zMailbox)
lb1.Items.Clear()
For Each txtfi In lynxin.GetFiles("*.txt")
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
ReDim Preserve AllDetail(0 To numfiles)
AllDetail(numfiles).uPath = 'Needs to be populated
AllDetail(numfiles).uName = 'Needs to be populated
AllDetail(numfiles).uCode = 'Needs to be populated
AllDetail(numfiles).uOps = 'Needs to be populated
lb1.Items.Add(IO.Path.GetFileNameWithoutExtension(txtfi.Name))
numfiles = numfiles + 1
Next
End Sub
AllDetail(numfiles).uPath = Would be the actual file path
AllDetail(numfiles).uName = Would be the detail after “unitname=”
AllDetail(numfiles).uCode = Would be the detail after “unitcode=”
AllDetail(numfiles).uOps = Would be the detail after “operation=”
Within the text files that are being read there will be the following lines
Unitname=
Unitcode=
Operation=
Requirements=
Dateplanned=
For the purpose of this array I just need the unitname, unitcode & operation. Going forward I will need the dateplanned as when this is working I want to try and work out how to only display the information if the dateplanned matches the date from a datepicker. Hope that helps and any guidance or tips are gratefully received
If your file is not very big you could simply
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
For each line in allLines
Dim parts = line.Split("="c)
if parts.Length = 2 andalso parts(0) = "unitname" Then
AllDetails(numFiles).uName = parts(1)
Exit For
End If
Next
If you are absolutely sure of the format of your input file, you could also use Linq to remove the explict for each
Dim line = allLines.Where(Function(x) (x.StartsWith("unitname"))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
EDIT
Looking at the last details added to your question I think you could rewrite your code in this way, but still a critical piece of info is missing.
What kind of object is supposed to be stored in the array AllDetails?
I suppose you have a class named FileDetail as this
Public class FileDetail
Public Dim uName As String
Public Dim uCode As String
Public Dim uCode As String
End Class
....
numfiles = 0
lb1.Items.Clear()
Dim lynxin As New IO.DirectoryInfo(zMailbox)
' Get the FileInfo array here and dimension the array for the size required
Dim allfiles = lynxin.GetFiles("*.txt")
' The array should contains elements of a class that have the appropriate properties
Dim AllDetails(allfiles.Count) as FileDetail
lb1.Items.Clear()
For Each txtfi In allfiles)
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
AllDetails(numFiles) = new FileDetail()
AllDetails(numFiles).uPath = txtfi.FullName
Dim line = allLines.Where(Function(x) (x.StartsWith("unitname="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
line = allLines.Where(Function(x) (x.StartsWith("unitcode="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
line = allLines.Where(Function(x) (x.StartsWith("operation="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uOps = line.Split("="c)(1)
End If
lb1.Items.Add(IO.Path.GetFileNameWithoutExtension(txtfi.Name))
numfiles = numfiles + 1
Next
Keep in mind that this code could be really simplified if you start using a List(Of FileDetails)