Can you help me on this? I want to get the section name and fields of my INI file. Example:
[connection]
server=localhost
user=root
password=root
My program should return the section name and the fields:
connection
server
user
password
Thanks in advance..
Just in case someone needs it. Here it is:
Dim path As String = Application.StartupPath & "\path_to_file"
' get a list of the files in this directory
' -----------------------------------------
Dim file_list As String() = Directory.GetFiles(path, "*.ini")
' go through the list of files
' -------------------------------------------------------------------
For Each f As String In file_list
Dim a = New System.IO.FileInfo(f).Name
' open the file and read it
' -------------------------
Dim sr As StreamReader = New StreamReader(f)
' read through the file line by line
' -----------------------------------
Do While sr.Peek() >= 0
Dim temp_name = Split(sr.ReadLine(), "=")
first_part = temp_name(0)
second_part = temp_name(1)
' do something with the information here
Loop
sr.Close()
Next
Related
I tried to write a code but I didn't succeed at all. Could someone help me please?
I want my program to read the data.txt file
The data.txt file contains:
Name: Christian
Phone: x
Address: x
Name: Alexander
Phone: x
Address: x
I would like the program to save the names in a output file: output_data.txt
The output_data.txt file should be contain:
Christian
Alexander
This is what I have so far:
Using DataReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("data.txt")
Dim DataSaver As System.IO.StreamWriter
DataReader.TextFieldType = FileIO.FieldType.Delimited
DataReader.SetDelimiters("Name: ")
Dim Row As String()
While Not DataReader.EndOfData
Row = DataReader.ReadFields()
Dim DataSplited As String
For Each DataSplited In Row
My.Computer.FileSystem.WriteAllText("output_data.txt", DataSplited, False)
'MsgBox(DataSplited)
Next
End While
End Using
But the output_data.txt file does not save properly to what "MsgBox (DataSplited)" shows. MsgBox(DataSplit) delimits the name by Name: but also shows the rest, such as address, phone. I don't know what the problem is.
this will work:
Dim strFile = "c:\test5\data.txt"
Dim InputBuf As String = File.ReadAllText(strFile)
Dim OutBuf As String = ""
Dim InBufHold() As String = Split(InputBuf, "Name:")
For i = 1 To InBufHold.Length - 1
OutBuf += Trim(Split(InBufHold(i), vbCrLf)(0)) & vbCrLf
Next
File.WriteAllText("c:\test5\output_data.txt", OutBuf)
Dim names = File.ReadLines("data.txt").
Where(Function(line) line.StartsWith("Name: ")).
Select(Function(line) line.SubString(5).Trim())
File.WriteAllText("output_data.txt", String.Join(vbCrLf, names))
This is a follow on question to Select block of text and merge into new document
I have a SGM document with comments added and comments in my sgm file. I need to extract the strings in between the start/stop comments so I can put them in a temporary file for modification. Right now it's selecting everything including the start/stop comments and data outside of the start/stop comments.
Dim DirFolder As String = txtDirectory.Text
Dim Directory As New IO.DirectoryInfo(DirFolder)
Dim allFiles As IO.FileInfo() = Directory.GetFiles("*.sgm")
Dim singleFile As IO.FileInfo
Dim Prefix As String
Dim newMasterFilePath As String
Dim masterFileName As String
Dim newMasterFileName As String
Dim startMark As String = "<!--#start#-->"
Dim stopMark As String = "<!--#stop#-->"
searchDir = txtDirectory.Text
Prefix = txtBxUnique.Text
For Each singleFile In allFiles
If File.Exists(singleFile.FullName) Then
Dim fileName = singleFile.FullName
Debug.Print("file name : " & fileName)
' A backup first
Dim backup As String = fileName & ".bak"
File.Copy(fileName, backup, True)
' Load lines from the source file in memory
Dim lines() As String = File.ReadAllLines(backup)
' Now re-create the source file and start writing lines inside a block
' Evaluate all the lines in the file.
' Set insideBlock to false
Dim insideBlock As Boolean = False
Using sw As StreamWriter = File.CreateText(backup)
For Each line As String In lines
If line = startMark Then
' start writing at the line below
insideBlock = True
' Evaluate if the next line is <!Stop>
ElseIf line = stopMark Then
' Stop writing
insideBlock = False
ElseIf insideBlock = True Then
' Write the current line in the block
sw.WriteLine(line)
End If
Next
End Using
End If
Next
This is the example text to test on.
<chapter id="Chapter_Overview"> <?Pub Lcl _divid="500" _parentid="0">
<title>Learning how to gather data</title>
<!--#start#-->
<section>
<title>ALTERNATE MISSION EQUIPMENT</title>
<para0 verdate="18 Jan 2019" verstatus="ver">
<title>
<applicabil applicref="xxx">
</applicabil>Three-Button Trackball Mouse</title>
<para>This is the example to grab all text between start and stop comments.
</para></para0>
</section>
<!--#stop#-->
Things to note: the start and stop comments ALWAYS fall on a new line, a document can have multiple start/stop sections
I thought maybe using a regex on this
(<section>[\w+\w]+.*?<\/section>)\R(<\?Pub _gtinsert.*>\R<pgbrk pgnum.*?>\R<\?Pub /_gtinsert>)*
Or maybe use IndexOf and LastIndexOf, but I couldn't get that working.
You can read the entire file and split it into an array using the string array of {"<!--#start#-->", "<!--#stop#-->"} to split, into this
Element 0: Text before "<!--#start#-->"
Element 1: Text between "<!--#start#-->" and "<!--#stop#-->"
Element 2: Text after "<!--#stop#-->"
and take element 1. Then write it to your backup.
Dim text = File.ReadAllText(backup).Split({startMark, stopMark}, StringSplitOptions.RemoveEmptyEntries)(1)
Using sw As StreamWriter = File.CreateText(backup)
sw.Write(text)
End Using
Edit to address comment
I did make the original code a little compact. It can be expanded out into the following, which allows you to add some validation
Dim text = File.ReadAllText(backup)
Dim split = text.Split({startMark, stopMark}, StringSplitOptions.RemoveEmptyEntries)
If split.Count() <> 3 Then Throw New Exception("File didn't contain one or more delimiters.")
text = split(1)
Using sw As StreamWriter = File.CreateText(backup)
sw.Write(text)
End Using
I'm trying to check if the file exists in the directory in which the application was saved and if so, to add a number at the end -1, -2. -3 - based on whether a file with the same name already exists. My code is below:
Dim FileName, FilePath As String
Dim FileNumber As Integer
FileName = ProjectName
FilePath = Path.Combine(CurrentDirectory, FileName)
If File.Exists(FilePath) = True Then
Do While File.Exists(FilePath)
FileNumber = FileNumber + 1
FileName = FileName & "-" & FileNumber
FilePath = Path.Combine(CurrentDirectory, FileName)
Loop
End If
NewWorkbook.SaveAs(FilePath)
When I run this code and the file is saving the first time, it works as intended but if I try saving the file with the same name a second time, there is no iterated FileNumber added to it, so the file name stays the same and it cannot save without replacing the original file.
Why is the File.Exists not recognizing that this file already exists and how can I fix this?
There is a logical problem in your code. You continue to modify the same variable and building continuosly new names.
For example. Suppose to have initially a file with the name "Project.vb". At the first iteration inside the loop you check for a file named "Project.vb1", if your loop continues at the second iteration you check for a file named "Project.vb12" and so on.
A more correct way could be
Dim FileName, FileWithoutExtension, FileExtension, FilePath As String
Dim FileNumber As Integer = 1
Dim currentDirectory As String = "E:\temp" ' as an example
FileName = "test.txt" ' as an example
FileExtension = Path.GetExtension(FileName)
FileWithoutExtension = Path.GetFileNameWithoutExtension(FileName)
FilePath = Path.Combine(CurrentDirectory, FileName)
' No need of additional if to test file existance.
Do While File.Exists(FilePath)
FileNumber = FileNumber + 1
' Rebuild the Filename part wtih all the info
FileName = FileWithoutExtension & "-" & FileNumber.ToString("D3") + FileExtension
FilePath = Path.Combine(CurrentDirectory, FileName)
Loop
NewWorkbook.SaveAs(FilePath)
I want to read and write the same file with StreamReader and StreamWriter. I know that in my code I am trying to open the file twice and that is the problem. Could anyone give me another way to do this? I got confused a bit.
As for the program, I wanted to create a program where I create a text if it doesnt exist. If it exists then it compares each line with a Listbox and see if the value from the Listbox appears there. If it doesnt then it will add to the text.
Dim SR As System.IO.StreamReader
Dim SW As System.IO.StreamWriter
SR = New System.IO.StreamReader("D:\temp\" & Cerberus.TextBox1.Text & "_deleted.txt", True)
SW = New System.IO.StreamWriter("D:\temp\" & Cerberus.TextBox1.Text & "_deleted.txt", True)
Dim strLine As String
Do While SR.Peek <> -1
strLine = SR.ReadLine()
For i = 0 To Cerberus.ListBox2.Items.Count - 1
If Cerberus.ListBox2.Items.Item(i).Contains(strLine) = False Then
SW.WriteLine(Cerberus.ListBox2.Items.Item(i))
End If
Next
Loop
SR.Close()
SW.Close()
SR.Dispose()
SW.Dispose()
MsgBox("Duplicates Removed!")
If your file is not that large, consider using File.ReadAllLines and File.WriteAllLines.
Dim path = "D:\temp\" & Cerberus.TextBox1.Text & "_deleted.txt"
Dim lines = File.ReadAllLines(path) 'String() -- holds all the lines in memory
Dim linesToWrite = Cerberus.ListBox2.Items.Cast(Of String).Except(lines)
File.AppendAllLines(path, linesToWrite)
If the file is large, but you only have to write a few lines, then you can use File.ReadLines:
Dim lines = File.ReadLines(path) 'IEnumerable(Of String)\
'holds only a single line in memory at a time
'but the file remains open until the iteration is finished
Dim linesToWrite = Cerberus.ListBox2.Items.Cast(Of String).Except(lines).ToList
File.AppendAllLines(path, linesToWrite)
If there are a large number of lines to write, then use the answers from this question.
I am trying to read file names from source directory and then read a separate file to rename and move files to target directory. Below code reads the file names but the problem is it only reading the contents of app.ini file only once i.e. for first file name. Code is not looping app.ini as soon as for loops switches to second file name.
Dim di As New IO.DirectoryInfo("D:\Transcend")
Dim diar1 As IO.FileInfo() = di.GetFiles()
Dim dra As IO.FileInfo
If (di.GetFiles.Count > 0) Then
Dim a As Integer = 1
Dim b As Integer = 1
For Each dra In diar1
ComboBox1.Items.Add(dra.FullName.ToString)
Using reader2 As New IO.StreamReader("D:\Transcend\test\app.ini")
Do While reader2.Peek() >= 0
Dim line2 = reader2.ReadLine
Do Until line2 Is Nothing
'line2 = reader2.ReadLine()
'ComboBox1.Items.Add(line2.ToString)
'Label1.Text = line2
If line2 <> Nothing Then
If line2.Contains("filename" + a.ToString) Then
Dim values() As String = line2.Split(CChar(":")).ToArray
Dim values2() As String = values(1).Split(CChar(";")).ToArray() 'full filename
Dim values3() As String = values(2).Split(CChar(";")).ToArray() 'keyword to be replaced in filename
Dim values4() As String = values(3).Split(CChar(";")).ToArray() 'fullname in place of keyword
Dim values5() As String = values(4).Split(CChar(";")).ToArray 'destination drive letter
Dim values6() As String = values(5).Split(CChar(";")).ToArray 'destination path after drive letter
ComboBox1.Items.Add(values2(0))
ComboBox1.Items.Add(values3(0))
ComboBox1.Items.Add(values4(0))
ComboBox1.Items.Add(values5(0) + ":" + values6(0))
'Label1.Text = dra.Name.ToString
If dra.Name.ToString.Contains(values2(0)) Then
Dim n As String = dra.Name.Replace(values3(0), values4(0))
File.Copy(dra.FullName, values5(0) + ":" + values6(0) + n)
End If
End If
End If
Exit Do
Loop
a = a + 1
Loop
reader2.Close()
End Using
b = b + 1
Next
Label1.Text = b
Else
MsgBox("No files!")
End
End If
ouput image:
Above image is to show the output and error, first line is the filename1 and the next 8 lines are the output of the app.ini file. As you can see as soon as the filename1 changes to the next file name i.e. Autorun.inf in the 9th line of the above image the same 8 lines of app.ini(line 2nd to 9th in the above image) should be reiterated after Autorun.inf file name but app.ini is not getting to read after file name increments to Autorun.inf and then to FreeSoftware(JF).htm.
The only difference between the first and the second file are the a and b values.
On the first run a will start from 1 and it will be incremented for each line in the app.ini file. After reading 8 lines, the final value of a will be 9.
For the second file, the value a isn't reset so it's value will still be 9. This means that the following condition will never be true because the first run only found value from 1 to 8 *.
If line2.Contains("filename" + a.ToString) Then
To fix your issue, you must set the a variable value back to 1 between each file:
Using reader2 As New IO.StreamReader("D:\Transcend\test\app.ini")
a = 1
Do While reader2.Peek() >= 0
* I'm assuming that the filename in your .ini file are sorted (i.e. line containing filename9 isn't listed before filename2) and that no external process changed the content of your .ini file between the first and the second file.