VB.Net read file content - vb.net

I'm trying to make an simple program to message box the executable that runs in "autorun.inf"
example:
[Autorun]
open=setup.exe
icon=setup.exe,0
how do i define the line which says
even if it's not the second line, it could be the 5th, i mean after some text..
open=setup.exe
and trim the file name and it's extension?

Dim FilePath As String = "E:\run.inf"
Dim INF As String = My.Computer.FileSystem.ReadAllText(FilePath)
INF = INF.ToLower
Dim StartIndex As Integer = INF.IndexOf("open=") + 5
Dim EndIndex As Integer = INF.IndexOf(vbCrLf, StartIndex)
Dim ExecutableName As String = ""
If StartIndex = 4 Then
MsgBox("the executable file name could not found at file :" & vbCrLf & FilePath)
Else
If EndIndex = -1 Then
ExecutableName = INF.Substring(StartIndex)
Else
ExecutableName = INF.Substring(StartIndex, EndIndex - StartIndex)
End If
MsgBox("The Executable Name is " & Chr(34) & ExecutableName & Chr(34))
End If
first we read all the text of the INF file and change its case to lower so that we can search through it for lower "open=".
and then we define the start index and the end index of the executable name as the start after string "open=" and the end before the newline vbCrlf.
and finally get Executable Name and show it in a MsgBox.

Related

How to search multiple text files in a directory for a string of text at once

I have a ListBox with a certain amount of items in it.
For each item in the ListBox a corresponding text file exists in the file directory.
I need to search each text file (based on what's in the ListBox) for a persons name. Each text file may contain the name or it may not.
I would then like a return which text file contains the name.
I have tried this as a way to search a text file: it works, but I'm not sure how to get this to repeat based on whats in a ListBox.
Dim sFileContents As String = String.Empty
If (System.IO.File.Exists((Application.StartupPath) & "\Project_Green.txt")) Then
sFileContents = (System.IO.File.ReadAllText((Application.StartupPath) & "\Project_Green.txt"))
End If
If sFileContents.Contains(TextBox4.Text) Then
MessageBox.Show("yup")
Else
MessageBox.Show("nope")
End If
Also, if it would be possible to ignore case that would be great.
If you have a bunch of files in a directory and you have their names in a ListBox, and you want to search their contents for something.
One liner query:
Imports System.IO
'...
Sub TheCaller()
Dim dir = My.Application.Info.DirectoryPath
Dim ext = ".txt" ' If the extensions are trimmed in the list.
Dim find = TextBox4.Text
Dim files = Directory.EnumerateFiles(dir).Where(Function(x) ListBox1.Items.Cast(Of String).
Any(Function(y) String.Concat(y, ext).
Equals(Path.GetFileName(x),
StringComparison.InvariantCultureIgnoreCase) AndAlso File.ReadLines(x).
Any(Function(z) z.IndexOf(find, StringComparison.InvariantCultureIgnoreCase) >= 0))).ToList
ListBox2.Items.Clear()
ListBox2.Items.AddRange(files.Select(Function(x) Path.GetFileNameWithoutExtension(x)).ToArray)
End Sub
Or if you prefer the For Each loop:
Sub Caller()
Dim dir = My.Application.Info.DirectoryPath
Dim find = TextBox4.Text
Dim files As New List(Of String)
For Each f As String In ListBox1.Items.Cast(Of String).
Select(Function(x) Path.Combine(dir, $"{x}.txt"))
If File.Exists(f) AndAlso
File.ReadLines(f).Any(Function(x) x.IndexOf(find,
StringComparison.InvariantCultureIgnoreCase) <> -1) Then
files.Add(f)
End If
Next
ListBox2.Items.Clear()
ListBox2.Items.AddRange(files.Select(Function(x) Path.GetFileNameWithoutExtension(x)).ToArray)
End Sub
Either way, the files list contains the matches if any.
Plus a pseudo-parallel async method, for the very heavy-duty name searches.
The Async Function SearchNameInTextFiles returns a named Tuple:
(FileName As String, Index As Integer)
where FileName is the file parsed and Index is the position where the first occurrence of the specified name (theName) was found.
If no matching sub-string is found, the Index value is set to -1.
The caseSensitive parameter allows to specify whether the match should be, well, case sensitive.
You can start the search from a Button.Click async handler (or similar), as shown here.
Imports System.IO
Imports System.Threading.Tasks
Private Async Sub btnSearchFiles_Click(sender As Object, e As EventArgs) Handles btnSearchFiles.Click
Dim filesPath = [Your files path]
Dim theName = textBox4.Text ' $" {textBox4.Text} " to match a whole word
Dim ext As String = ".txt" ' Or String.Empty, if extension is already included
Dim tasks = ListBox1.Items.OfType(Of String).
Select(Function(f) SearchNameInTextFiles(Path.Combine(filesPath, f & ext), theName, False)).ToList()
Await Task.WhenAll(tasks)
Dim results = tasks.Where(Function(t) t.Result.Index >= 0).Select(Function(t) t.Result).ToList()
results.ForEach(Sub(r) Console.WriteLine($"File: {r.FileName}, Position: {r.Index}"))
End Sub
Private Async Function SearchNameInTextFiles(filePath As String, nameToSearch As String, caseSensitive As Boolean) As Task(Of (FileName As String, Index As Integer))
If Not File.Exists(filePath) then Return (filePath, -1)
Using reader As StreamReader = New StreamReader(filePath)
Dim line As String = String.Empty
Dim linesLength As Integer = 0
Dim comparison = If(caseSensitive, StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase)
While Not reader.EndOfStream
line = Await reader.ReadLineAsync()
Dim position As Integer = line.IndexOf(nameToSearch, comparison)
If position > 0 Then Return (filePath, linesLength + position)
linesLength += line.Length
End While
Return (filePath, -1)
End Using
End Function
You can do these simple steps for your purpose:
First get all text files in the application's startup directory.
Then iterate over all names in the ListBox and for each one, search in all text files to find the file that contains that name.
To make the process case-insensitive, we first convert names and text file's contents to "lower case" and then compare them. Here is the full code:
Private Sub findTextFile()
'1- Get all text files in the directory
Dim myDirInfo As New IO.DirectoryInfo(Application.StartupPath)
Dim allTextFiles As IO.FileInfo() = myDirInfo.GetFiles("*.txt")
'2- Iterate over all names in the ListBox
For Each name As String In ListBox1.Items
'Open text files one-by-one and find the first text file that contains this name
Dim found As Boolean = False 'Changes to true once the name is found in a text file
Dim containingFile As String = ""
For Each file As IO.FileInfo In allTextFiles
If System.IO.File.ReadAllText(file.FullName).ToLower.Contains(name.ToLower) Then 'compares case-insensitive
found = True
containingFile = file.FullName
Exit For
End If
Next
'Found?
If found Then
MsgBox("The name '" + name + "' found in:" + vbNewLine + containingFile)
Else
MsgBox("The name '" + name + "' does not exist in any text file.")
End If
Next
End Sub

How To Replace or Write the Sentence Backwards

I would like to have a block of code or a function in vb.net which can write a sentence backwards.
For example : i love visual basic
Result : basic visual love i
This is what I have so far:
Dim name As String
Dim namereversed As String
name = RichTextBox1.Text
namereversed = ""
Dim i As Integer
For i = Len(name) To 1 Step -1
namereversed = namereversed & Replace(name, i, 1)
Next
RichTextBox2.Text = namereversed
The code works but it does not give me the value of what i want. it makes the whole words reversed.
Dim name As String = "i love visual basic"
Dim reversedName As String = ""
Dim tempName As String = ""
For i As Integer = 0 To name.Length - 1
If Not name.Substring(i, 1).Trim.Equals("") Then
tempName += name.Substring(i, 1)
Else
reversedName = tempName + " " + reversedName
tempName = ""
End If
Next
start from index 0 and deduct 1 from length because length count starts with one but index count starts with zero. if you put To name.Length it will return IndexOutOfBounds. Loop it from 0 To Length-1 because you need the word as is and not spelled backwards... what are placed in reverse are the words so add a temporary String variable that stores every word and add it before the saved sentence/words.
or use this
Dim strName As String() = name.Split(" ")
Array.Reverse(strName)
reversedName = String.Join(" ", strName)
This is my contribution, well as you can see its not hard to do, its really simple. There are a lot of other ways which are more short.
Console.Title = "Text Reverser"
Console.ForegroundColor = ConsoleColor.Green
'Text which will be Reversed
Dim Text As String
Console.Write("Write your text: ")
Text = Console.ReadLine
Console.Clear()
Dim RevText As String = "" '← The Text that will be reversed
Dim Index As Int32 = Text.Length '← Index used to write backwards
'Fill RevText with a char
Do Until RevText.Length = Text.Length
RevText = RevText.Insert(0, "§")
Loop
Console.WriteLine(RevText)
'Replace "Spaces" with Character, using 'Index' to know where go the chars
For Each Caracter As Char In Text
Index -= 1 'Rest 1 from the Index
RevText = RevText.Insert(Index, Caracter) '← Put next char in the reversed text
'↓ Finished reversing the text
If Index = 0 Then
RevText = RevText.Replace("§", "") 'Replace char counter to nothing
Console.WriteLine("Your text reversed: " & RevText) '← When Index its 0 then write the RevText
End If
Next
'Pause
Console.ReadKey()
I've done this project in a console, but you know, you can use this code in a normal Windows Form.
This is my first Answer in Stackoverflow :)

All SubDirectories and a file count for each in a lable

How can i have the list of all SubDirectories and for each SubDirectory a file count?
And most important it must be in a form of continuos text, not as a listbox.
My example just prints the last Directory. How can i get it to print them all like this:
Adobe: 45 / Adobe Media Player:5 / Java: 22 / etc....
Private Sub GetDir()
For Each x As String In System.IO.Directory.GetDirectories("C:\ProgramFiles")
y = x & " : " & CStr(x.Count)
Next
Label1.Text = y
End Sub
I need it in continuos text so i can mail it actually. That's why i can't work with listbox.
You can use a StringBuilder object to build the output and a DirectoryInfo object to easily get name and files count for each directory.
Dim list As New StringBuilder
For Each directory As String In IO.Directory.GetDirectories("C:\ProgramFiles")
Dim subDirectory As New IO.DirectoryInfo(directory)
list.Append(subDirectory.Name & ": " & subDirectory.GetFiles.Length & " / ")
Next
Dim text As String = list.ToString.Remove(list.Length - 3)
I had to add a space to "Program Files" or it was blowing up, but the += should add to your string in the loop fine.
Private Sub GetDir()
Dim y As String = ""
For Each dir As String In System.IO.Directory.GetDirectories("C:\Program Files")
y += dir & " : " & CStr(dir.Count)
Next
Label1.Text = y
End Sub

Compare contents of a text file based on line number VB2008

Let's say I have two text file, I will compare (based on the line numbering of text ->see below) because this is where the unique key is generated.
sample1.txt:
5th line -> _000_000F_01CE2577.B840E640
sample2.txt
5th line -> _000_000F_01CE2577.B840E640
Now here is my code:
Dim FILE_NAME As String = "C:\myfiles"
'This is to determine the number of lines in the text file
Dim count As Integer
count = 0
Dim obj As StreamReader
obj = New StreamReader(FILE_NAME)
Do Until obj.ReadLine Is Nothing
count = count + 1
Loop
'------------------------------
'this is my computation to get the number of line -->disregard this
Dim temp3 As Integer
temp3 = count - 3
'------------------------------
obj.Close()
'This is to read all the text in the text file
Dim fileReader(fs) As String
fileReader(fs) = My.Computer.FileSystem.ReadAllText(FILE_NAME, _
System.Text.Encoding.ASCII)
I have stored each file in an array
Example:
file[0]
file[1]
Then I have to read each file and its contents, now how will i compare the line of text to each other. i believe i have to use regex.
Please give me some pointers on how to compare the line of text...
e.g. 5th line in sample1.txt == 5th line of sample2.txt
I have to know if they are the same.
this should do the job for you
it will read each line in txt file , save it to an array then compare
note: set paths do your 2 txt files
it will go out of bounds if there is less lines in file 2 than file 1. You can add a little bit of code to handle that case though.
Option Explicit
Sub Read_text_File()
Dim firstFile() As String, secondFile() As String
Dim path1 As String, path2 As String
Dim i As Long
path1 = "C:\ ... .txt"
path2 = "C:\ ... .txt"
Call fill_array(firstFile, path1)
Call fill_array(secondFile, path2)
For i = LBound(firstFile) To UBound(firstFile) - 1
Debug.Print (firstFile(i) & vbTab & vbTab & vbTab & vbTab & secondFile(i))
If StrComp(firstFile(i), secondFile(i), vbTextCompare) = 0 Then
MsgBox "Line: " & i + 1 & " matches "
End If
Next i
End Sub
Sub fill_array(ByRef arr() As String, pathToFile As String)
Dim oFSO As New FileSystemObject
Dim oFS As TextStream
Dim cnt As Long
cnt = 0
Set oFS = oFSO.OpenTextFile(pathToFile)
Do Until oFS.AtEndOfStream
oFS.ReadLine
cnt = cnt + 1
Loop
ReDim arr(cnt)
Set oFS = oFSO.OpenTextFile(pathToFile)
cnt = 0
Do Until oFS.AtEndOfStream
arr(cnt) = oFS.ReadLine
cnt = cnt + 1
Loop
oFS.Close
Set oFS = Nothing
End Sub

Splitting a string based on a set length of characters

MVC 3. Vb.net. Part of my app generates PDF files using Itextsharp. Some strings are too long to go onto the background image correctly. So I basically need to split this string when its over 26 characters long and when it splits it cant split in the middle of a word. from there I will use newline to add the string to the right to the next line... Any ideas that might point me in the right direction.. I did start bulding the function that I will pass the string into test for length and then pass back the string after it finishes but I am stummped after that..
Private Function stringLength(ByVal _string As String) As String
If _string.Length < 26 Then
_string.Split(
End If
End Function
I'm sure there's a million different ways to do this.
You basically need to get all of your words split by the space into a list. After that, you just need to keep checking if the current word plus a space plus the next word reach your threshold or not, and if it does, you move to the next line. Once you have all of your lines, then you rejoin the list into a single string again.
Private Function LimitWidth(ByVal text As String, ByVal maxCharacters As Integer) As String
Dim words As List(Of String) = text.Split(" "c).ToList()
If text.Length < maxCharacters OrElse words.Count = 1 Then
Return text
Else
Dim lines As New List(Of String)
Dim currentLine As String = words(0)
For i As Integer = 1 To words.Count - 1
If (currentLine & " " & words(i)).Length > maxCharacters Then
lines.Add(currentLine)
currentLine = words(i)
If i = words.Count - 1 Then
lines.Add(currentLine)
End If
Else
If i = words.Count - 1 Then
lines.Add(currentLine & " " & words(i))
End If
currentLine &= " " & words(i)
End If
Next
Return String.Join(Environment.NewLine, lines.ToArray())
End If
End Function
To Test:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
MessageBox.Show(LimitWidth("This is a really long sentence " & _
"meant to demonstrate how to split " & _
"the words into a confined character length.", 26))
End Sub
It sounds like you are asking for a word wrap function.
Since I feel that it's better to answer in a way that promotes learning than to just give answers, I have for you a link that walks you through the process of using Test Driven Development (TDD) to solve this problem. It just so happens that the word wrap problem is a popular coding kata, and Robert C. Martin wrote a somewhat silly fictional story about a developer being taught how to use TDD to solve the word wrap kata.
The code examples are in Java, but it should be trivial to read and translate.
http://thecleancoder.blogspot.com/2010/10/craftsman-62-dark-path.html
The goofy bits are skip-able. Just jump down to the sentences right before the first code snippet.
I would add to it handling of multiline input text with following:
Private Function LimitWidth(ByVal text As String, ByVal maxCharacters As Integer, SplitSign As String) As String
Dim Output As String = ""
Dim OrgLines As List(Of String) = text.Split(Environment.NewLine).ToList()
For x As Integer = 1 To OrgLines.Count - 1
Dim words As List(Of String) = OrgLines(x).Split(" "c).ToList()
If text.Length < maxCharacters OrElse words.Count = 1 Then
Output += OrgLines(x)
Else
Dim lines As New List(Of String)
Dim currentLine As String = words(0)
For i As Integer = 1 To words.Count - 1
If (currentLine & " " & words(i)).Length > maxCharacters Then
lines.Add(currentLine)
currentLine = words(i)
If i = words.Count - 1 Then
lines.Add(currentLine)
End If
Else
If i = words.Count - 1 Then
lines.Add(currentLine & " " & words(i))
End If
currentLine &= " " & words(i)
End If
Next
Output += String.Join(SplitSign, lines.ToArray())
End If
Next
Return Output
End Function
use:
LimitWidth("your text", 80, Environment.NewLine)