read specific values from text file - vb.net

I have the following visual basic code, which is part of a custom class. I want a simple and effective way(use little computer resources) to assign the "value1" value(100) to "_field1","value2" value(8) to "_field2" etc. Any nice ideas? thanks
Private Sub readcrnFile()
'read files and assing values to the properties
Dim sr As New IO.StreamReader(_fileName)
_field1 = sr.ReadToEnd()
_field2 = sr.ReadToEnd()
_field3 = sr.ReadToEnd()
sr.Close()
End Sub
where _fileName is a full path to a text file which looks like this:
value1: 100
value2: 8
value3: 80

Private Sub readcrnFile()
Dim lines = File.ReadLines(_fileName)
For Each line In lines
Dim val = line.Split(":")(1).Trim
'do something with val?
Next
End Sub
Returning a dictionary is trivial:
Private Sub readcrnFile()
Dim dict = File.ReadLines(_fileName).Select(Function(line) line.Split(":")).ToDictionary(Function(parts) parts(0).Trim, Function(parts) parts(1).Trim)
Debug.WriteLine(dict("value1")) 'will print 100
End Sub

Change your _field1, _field2 and _field3 variables to a List(Of String) (i.e. named field) and access to each field using its index (field(0), field(1), field(2)).
Dim field As New List(Of String)
Private Sub readcrnFile()
For Each line In File.ReadAllLines(_filename)
For i = 1 To 3
If line.Contains("value" & i) Then
field.Add(line.Substring(line.IndexOf(":") + 2))
End If
Next
Next
End Sub

Related

Question in save image to folder from listview for vb.net

Dim path As String = "c:\Mahesh" & TextBox1.Text
If Not Directory.Exists(path) Then
Directory.CreateDirectory(path)
' Dim i As Integer
For i = 0 To ImageList1.Images.Count - 1
FileCopy(ImageList1.Image.FromFile(path))
ImageList1.Images.Add(Image.FromFile(path))
Next
Else
MsgBox("خطأ")
End If
You can save every image object with the Image.Save method.
In this case, you have to write something similar to this:
Private sub SavePNGFromImageList1(imgIndex as integer, path as String)
ImageList1.Images(imgIndex).Save(path, System.Drawing.Imaging.ImageFormat.Png)
End sub
You can use different image formats (see ImageFormat class)

I want to have extra characters that will serve as divider my to string

Sub SaveInLogs(isThereNewLogs As Boolean, value As String)
Dim list As List(Of String)
Try
list = Strings.Split(value, "#-!-#").ToList
list(2) = "Incoming"
For Each word In list
MsgBox(list)
Next
Catch ex As Exception
End Try
End Sub
The value of paramater "value" is this :
7/28/2016 10:19:27 AM#-!-#Alex17282016#-!-#Outgoing#-!-#Alex#-!-#Alex#-!-#Text#-!-#1ST
Then I split the values and change the word Outgoing to Incoming.
Now I want my string to to look like this again
7/28/2016 10:19:27 AM#-!-#Alex17282016#-!-#Incoming#-!-#Alex#-!-#Alex#-!-#Text#-!-#1ST
Sorry for my grammar. I hope you understand my question
Below I have edited your code you already have to make the string the way you want it after changing "Outgoing" to "Incoming":
Sub SaveInLogs(isThereNewLogs As Boolean, value As String)
Dim list As List(Of String)
Dim newValue as String = ""
Try
list = Strings.Split(value, "#-!-#").ToList
list(2) = "Incoming"
For Each word In list
newValue = newValue & word
Next
value = newValue
Catch ex As Exception
End Try
End Sub
Or as Mark in the comments stated you could use string.join instead of a loop:
Sub SaveInLogs(isThereNewLogs As Boolean, value As String)
Dim list As List(Of String)
Try
list = Strings.Split(value, "#-!-#").ToList
list(2) = "Incoming"
Dim newValue As String = String.Join("#-!-#", list)
Catch ex As Exception
End Try
End Sub
Below is code I think would work better, as it does it one line of code and doesn't need to split the string apart and put it back together:
Sub SaveInLogs(isThereNewLogs As Boolean, value As String)
value = value.replace("#-!-#Outgoing#-!-#", "#-!-#Incoming#-!-#")
End Sub

Appending a csv file

Dim NumberOfRecords As Integer
Sub Main()
Call ListTowns()
End Sub
Sub ListTowns()
Dim FileName As String
Dim MyFormat As String = "{0, -22} {1, -16} {2, -8} {3, -8}"
FileName = "Towns.csv"
Dim AllRecords As String() = System.IO.File.ReadAllLines(FileName)
Dim TownList = From record In AllRecords
Let field = record.Split(",")
Select New With {.Name = field(0), .County = field(1), .Population = field(2), .Area = field(3)}
For Each Town In TownList
Console.WriteLine(String.Format(MyFormat, Town.Name, Town.County, Town.Population, Town.Area))
Next
NumberOfRecords = TownList.Count
Console.ReadLine()
End Sub
Sub AddRecord()
Dim FileName As String
FileName = "C:\Users\Omar\Desktop\Towns.csv"
FileOpen(1, FileName, OpenMode.Random)
Dim NewRecord As String
Console.WriteLine("Enter the record you want add")
NewRecord = Console.ReadLine()
FilePut(1, NewRecord, NumberOfRecords + 1)
FileClose(1)
Console.WriteLine("The record has been added")
Console.ReadLine()
End Sub
At the moment the program can list the contents of the csv file however with regard to the AddRecord() Sub, when I input the data Test,Test,Test,Test it is adding this record to the file properly and is overwriting the first record.
How do I fix this?
OpenMode.Random is used for reading/writing files that have a fixed width record. It is unclear from your post if you actually have fixed width records (my hunch is you don't). At any rate, to properly read/write in random mode you'd have to declare a structure that defines the length of each record and also tell the system the length of the record when you open it (so that it can move that many bytes to the desired record position you want to read/write!). Follow the links listed in this page titled Random File Access to learn how to do this.
If you don't actually have fixed width records, but instead have variable length records (one record per line, and the lines are different lengths), then you can simply store all the lines in a List(Of String) and add the new record to the end of the List. Now you simply overwrite the entire file with System.IO.File.WriteAllLines(), similar to what you did with ReadAllLines(). With this approach, you can modify any of the records in the List and then simply overwrite the entire file to update the physical file.
Here's a quick example of what the second approach might look like:
Module Module1
Public AllRecords As New List(Of String)
Public FileName As String = "C:\Users\Omar\Desktop\Towns.csv"
Public Sub Main()
LoadTowns()
ListTowns()
AddRecord()
ListTowns()
End Sub
Public Sub LoadTowns()
AllRecords.Clear()
AllRecords.AddRange(System.IO.File.ReadAllLines(FileName))
End Sub
Public Sub ListTowns()
Dim MyFormat As String = "{0, -22} {1, -16} {2, -8} {3, -8}"
Dim TownList = From record In AllRecords
Let field = record.Split(",")
Select New With {.Name = field(0), .County = field(1), .Population = field(2), .Area = field(3)}
For Each Town In TownList
Console.WriteLine(String.Format(MyFormat, Town.Name, Town.County, Town.Population, Town.Area))
Next
Console.ReadLine()
End Sub
Public Sub AddRecord()
Console.WriteLine("Enter the record you want add")
Dim NewRecord As String = Console.ReadLine()
AllRecords.Add(NewRecord)
System.IO.File.WriteAllLines(FileName, AllRecords.ToArray)
Console.WriteLine("The record has been added")
Console.ReadLine()
End Sub
End Module

vb.net - How to Declare new task as SUB with parameters

As you know we have a new syntax in vb.net with possibility to create inline tasks so we could run it asynchronously.
This is the correct code:
Dim testDeclaring As New Task(Sub()
End Sub)
testDeclaring.Start()
but now I need to pass a parameter in the subroutine and I can't find correct syntax for that.
Is it possible any way?
It's not possible. However, you could just use the parameters from the current scope:
Public Function SomeFunction()
Dim somevariable as Integer = 5
Dim testDeclaring As New Task(Sub()
Dim sum as integer = somevariable + 1 ' No problems here, sum will be 6
End Sub)
testDeclaring.Start()
End Function
If you want to pass a parameter you could do this
Dim someAction As Action(Of Object) = Sub(s As Object)
Debug.WriteLine(DirectCast(s, String))
End Sub
Dim testDeclaring As New Task(someAction, "tryme")
testDeclaring.Start()
Dont know if you looking for this:
Dim t As Task = New Task(Sub() RemoveBreakPages(doc))
Sub RemoveBreakPages(ByRef doc As Document)
Dim paragraphs As NodeCollection = doc.GetChildNodes(NodeType.Paragraph, True)
Dim runs As NodeCollection = doc.GetChildNodes(NodeType.Run, True)
For Each p In paragraphs
If CType(p, Paragraph).ParagraphFormat().PageBreakBefore() Then
CType(p, Paragraph).ParagraphFormat().PageBreakBefore = False
End If
Next
End Sub
Regards.

Search engine in vb.net

I am building a search engine in vb.net which would have to search for a word entered by the user in 40 text files within the project directory.
It should return the results as the total number of matches (text files) and the number of times this word is in each file. Any suggestions for a start would be grateful.
Regards.
get a list of the files in the directory with something like: Directory.GetFiles(ProjectDir, "*.*"), then read each file in the list like this:
Dim sr As StreamReader = New StreamReader(fileName)
Dim line As String
Do
line = sr.ReadLine()
scan the line and count
Loop Until line Is Nothing
sr.Close()
Try this code, in a console application, not only could find a word
even you can get the results using a RegEx Expression.
Class TextFileInfo
Public File As System.IO.FileInfo
public Count As Integer
public FileText As String
public ItMatch as Boolean = False
Sub New (FileFullName as String,WordPattern as String)
File = new System.IO.FileInfo(FileFullName)
Using Fs As System.IO.StreamReader(File.FullName)
FileText = Fs.ReadToEnd()'//===>Read Text
End Using
Count = _CountWords(WordPattern,FileText)
ItMatch = Count > 0
End Sub
Public Sub DisplayInfo()
System.Console.WriteLine("File Name:" + File.Name)
System.Console.WriteLine("Matched Times:" & Count)
End Sub
Private Function _CountWords(Word As String,Text As String) as Integer
Dim RegEx as System.Text.RegularExpressions.Regex(Word)
return RegEx.Matches(Text).Count'//===>Returns how many times this word match in the Text
End Fuction
End Class
Public Function SearchEngine(PatternWord As String,RootDirectory As String) List(Of TextFileInfo)
Dim MatchedFiles As New List(Of TextFileInfo)
Dim RootDir As New System.IO.DirectoryInfo(RootDirectory)
For Each iTextFile as System.IO.FileInfo In RootDir.GetFiles("*.txt")
'//===>Create a object of TextFileInfo and check if the file contains the word
Dim iMatchFile as New TextFileInfo(iTextFiles.FullName,PatternWord)
If iMatchFile.ItMatch Then
'//===>Add the object to the list if it has been matches
MatchedFiles.Add(iMatchFile)
End If
Loop
retur MatchedFiles '//===>Return the results of the files that has the matched word
End Function
Sub Main()
Dim SearchResults as List(Of TextFileInfo) = SearchEngine("JajajaWord","C:\TextFiles\")
For Each iSearch As TextFileInfo In SearchResults
iSearch.DisplayInfo()
Loop
End Sub