Read and Write to specific line in textfile with VB.Net - vb.net

So here is my problem:
1st I need to read a text file and get the line number 5
System.IO.File.ReadAllText("E:\myFile.txt")
My text file its something like this:
ABCDE "2015"
GDFTHRE "0.25 0.25"
TRYIP "192.168.1.6"
WIDTH "69222"
ORIGIN "200"
So, what i need is to replace the value 200, lets say 250 and keep the line as this: ORIGIN "250"
I have tryed with the Replace but i can't get it.

If your text file is divided into lines and you only want to look at the 5th line, you can use ReadAllLines to read the lines into an array of String. Process line 4 (the 5th line) and use WriteAllLines to re-write the file. The following example checks that the file contains at least 5 lines and that the 5th line begins with "ORIGIN "; if so it replaces the line with ORIGIN "250" and re-writes the file.
Dim filePath As String = "E:\myFile.txt"
Dim lines() As String = System.IO.File.ReadAllLines(filePath)
If lines.Length > 4 AndAlso lines(4).StartsWith("ORIGIN ") Then
lines(4) = "ORIGIN ""250"""
System.IO.File.WriteAllLines(filePath, lines)
End If

You can simply replace the text and then write everything back to the file again:
Dim content As String
' read all text from the file to the content variable
content = System.IO.File.ReadAllText("E:\myFile.txt")
' replace number, text, etc. in code
content = content.Replace("<string to replace>","<replace with>")
' write new text back to the file (by completely overwriting the old content)
System.IO.File.WriteAllText("E:\myFile.txt",content)

Related

Trying to close textfile after line is read

Im trying to output the data from the second line of my textfile to a datagridview but when doing so it is also outputting every line after the the second line. This is what I have tried. Thanks
Dim lines = IO.File.ReadAllLines(OrderID & ".txt")
For index = 1 To lines.Length - 1
Dim cells = lines(index).Split(","c)
dgvOutput.Rows.Add(cells)
FileClose()
It's outputting every line after the second line, because that's what you're telling it to do when you iterate through the array of strings returns from ReadAllLines.
IO.File.ReadAllLines does not leave an output stream open. The file is closed. What it does do, is return a zero-based (by default) array of the contents of the file, with line breaks being the delimiter for the split.
To just get the contents of the second line, using ReadAllLines, this is what you need:
Dim lines = IO.File.ReadAllLines(OrderID & ".txt")
If lines.length >= 2 Then
Dim cells = lines(1).Split(","c)
dgvOutput.Rows.Add(cells)
End If
Now, that does have the overhead of reading the entire file in. If you open the file using a reader object, then you only need to read the first and second lines of the file to get that second line.
That would be something like this:
Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(OrderId & ".txt")
Dim a as String
' This reads the first line, which we throw away
reader.ReadLine()
a = reader.ReadLine()
reader.Close()
Dim cells = a.Split(","c)
dgvOutput.Rows.Add(cells)
You would need to test your explicit circumstances to determine which is better for what you're trying to do.
Your loop is executed over all lines skipping just the first line.
While I cannot see what happen in the FileClose call it seems to not have any sense because ReadAllLines has already closed the file.
You can get the second line of your file with a single line of code
Dim line as String = File.ReadLines(OrderID & ".txt").Skip(1).Take(1).FirstOrDefault()
' this check is required to avoid problems with files containing 0 or 1 line
if line IsNot Nothing Then
Dim cells = line.Split(","c)
dgvOutput.Rows.Add(cells)
End If
Notice that I have replaced the ReadAllLines with ReadLines. This is better because using this method you don't read all lines when you need only the second one (if it exists). More info at ReadLines vs ReadAllLines
Dim lines = IO.File.ReadAllLines(OrderID & ".txt")
Dim SecondLine = lines(1)
File.ReadAllLines opens and closes the file for you so there is not need to add code to close it.

Reset index of File object for reading several time

Now, I am writing a VBA program. In my program, firstly I need to count all line from a file. I need line count because of creating array for line in file. So, I used this code. It is OK.
'Open file
Set file = fsObject.OpenTextFile(filePath, ForReading)
'Read all line
file.ReadAll
'Get line count
lineCount = file.line
'Close file
file.Close
After getting line count, I want to subtract 2 from it for header and footer(the blank line). I don't know which word will be header. I only know row that they are first row and last row(the blank row).
'Remove header and blank line from line count
lineCount = lineCount - 2
And then, I wanna read that file line by line which are only useful for me and store all line in array. The problem is at that, when reading line by line, It is need to re-open file. Only after re-open, I can read line by line.
Because, "ReadAll" method is readed all line and the index of file object is shown "AtEndOfFile". So, I must re-open it. Please check my code.
'If line count is greater than 0, read again file to get data
If lineCount > 0 Then
'Re-define array size
ReDim lineList(lineCount) As String
'Here I opend it, I don't wanna open. I just want to set index of file object.
'Re-open file
Set file = fsObject.OpenTextFile(filePath, ForReading)
'Read file until end
Do Until file.AtEndOfStream
'If current line is not first line(header) or last line(blank line)
If line <> 0 And line <= lineCount Then
'Store line into array
lineList(index) = file.ReadLine
'Increase array index
index = index + 1
Else
file.ReadLine
End If
'Increase line index
line = line + 1
Loop
End If
But, I want another way. I don't wanna re-open file. I want to reset the index to the first line of file object. So, I don't need to re-open it.
I already search about it in internet. But, I didn't found any suggestions for that. Please help me. Thanks.
My approach is slightly different than your current approach, I would use the Binary read to read the file and save it in a temporary string, then use Split function to put them in an Array.
This method has one drawback as in the if the length (number of characters) of the file is greater than the size of a String variable then we might have issues but other than that. This is quite different approach.
Public Sub ReadFileData(filePath As String, Optional separatorStr As String = ";#;")
'******************************************************************************
' Opens a large TXT File, reads the data until EOF on the Source,
' then stores them in an Array
' Arguments:
' ``````````
' 1. The Source File Path - "C:\Users\SO\FileName.Txt" (or) D:\Data.txt
' 2. (Optional) Separator - The separator, you wish to use. Defauls to ';#;'
'*******************************************************************************
Dim strIn As String, tmpStr As String, lineCtr As Long
Dim tmpArr() As String
Open filePath For Input As #1
Do While Not EOF(1)
'Read one line at a time.
Line Input #1, strIn
tmpStr = tmpStr & Trim(strIn) & separatorStr
lineCtr = lineCtr + 1
Loop
Close #1
tmpArr = Split(tmpStr, separatorStr)
Debug.Print "Number of Elements in the Arrays is - " & UBound(tmpArr)
Debug.Print "Number of Lines Read is - " & lineCtr
End Sub

Reading and writing lines to and from a file

I am writing a simple console application using Microsoft Visual Basic 2010 express. I am trying to make a "newfile1.txt" file in which will be write something heading and than lets say 10 rows with three words in each row.
After that, I would like to read from file, and write to the "newfile2" file only the second word from file "newfile1.txt"
Than I would like to read from this file every line, and store lets and store only the second word from newfile1.txt
I try to use following code but I don't know how to specify several things (see bellow code)
Module Module1
Sub Main()
Dim i As Integer
FileOpen(1, "C:\Users\Namba\Documents\ANALYZA MD\newFile1.txt", OpenMode.Append, OpenAccess.ReadWrite, OpenShare.Default)
FileOpen(2, "C:\Users\Namba\Documents\ANALYZA MD\newFile2.txt", OpenMode.Append, OpenAccess.ReadWrite, OpenShare.Default)
WriteLine(1, "Heading of the file1")
For i = 1 To 10 Step 1
WriteLine(1, "Word 1" & "Word 2" & "Word 3")
Next
FileClose(1)
WriteLine(2, "Heading of the file2")
Dim filereader As System.IO.StreamReader
filereader = My.Computer.FileSystem.OpenTextFileReader("C:\Users\Namba\Documents\ANALYZA MD\newFile1.txt")
Dim stringReader As String
For i = 1 To 10 Step 1
stringReader = filereader.ReadLine()
WriteLine(2, stringReader)
Next
End Sub
End Module
So I have several questions:
Is it possible via ReadLine store words lets say in to the array or each word to the different string variable?
Is there simpler form how to open file and read each word, eventual define that the first word will be store in to the string var1, the second in to the var2 and so on, and similar if we have a file with numbers so that I would like to read from this file and store each number in to the some variable.
I can do this in fortran easy, via READ() WRITE() in very simple way
OPEN(UNIT=11, FILE="newfile1.txt)
READ(UNIT=11) x, y, z
OPEN(UNIT=12, FILE="newfile2.txt)
WRITE(UNIT=12,*) y
So this will read from one file the first 3 word(or number if the x, y, z is declare as number) from the first line and write in to the second file just second word (or number).
So I wonder if there is something very similar also in visual basic?
In general, if your files aren't large then it is faster (with respect to code writing) and easier to just read the contents of the file into memory and then manipulate it as needed.
Hopefully these examples will be of some help.
' Read entire contents of file1.txt into an array.
Dim file1 As String() = System.IO.File.ReadAllLines("C:\file1.txt")
' Now extract the 2nd word from each line (assuming all lines have at least 2 words).
Dim secondWords As New List(Of String)
For Each line In file1
' Break apart the string by spaces and take the second index (word).
secondWords.Add(line.Split(" ")(1))
Next
' Write the contents to a new file.
' This new file will have 1 word per line.
System.IO.File.WriteAllLines("C:\file2.txt", secondWords.ToArray())
If you are looking to examine each word, the code can become something like this:
' Read entire contents of file1.txt into an array.
Dim file1 As String() = System.IO.File.ReadAllLines("C:\file1.txt")
' Process each line.
For Each line In file1
' Process each word within the line.
For Each word In line.Split(" ")
' Do something with the word.
Console.WriteLine(word)
Next
' Or process by word index.
Dim words As String() = line.Split(" ")
For i As Integer = 0 To words.Length - 1
Console.WriteLine(String.Format("Word {0} is {1}", i + 1, words(i)))
Next
Console.WriteLine("Moving to a new line.")
Next

Write to a specific line in txt file when the line is empty

I am working on file writing in Vb.net. I know how to override a specific line in a text file but when it is empty or equal to "" , it fails.
I tried with
Dim lines() As String = System.IO.File.ReadAllLines("filepath")
lines(4) = "to replace text"
System.IO.File.WriteAllLines(filepath, lines)
It shows a Index out of array exception. It might be because the line in the file is empty.
Thank you

trying to read a delimited text file from resources - but it wont run

I'm having a problem where instead of reading a text file from the location string, I changed it to read the text file from the resource location and it breaks my program. I've also used the insert snippet method to get most of this code, so it is safe to say I don't know what is going on. Could some one please help?
'reads the text out of a delimited text file and puts the words and hints into to separate arrays
' this works and made the program run
' Dim filename As String = Application.StartupPath + "\ProggramingList.txt"
'this dosnt work and brings back a Illegal characters in path error.
dim filename as string = My.Resources.ProggramingList
Dim fields As String()
'my text files are delimited
Dim delimiter As String = ","
Using parser As New TextFieldParser(filename)
parser.SetDelimiters(delimiter)
While Not parser.EndOfData
' Read in the fields for the current line
fields = parser.ReadFields()
' Add code here to use data in fields variable.
'put the result into two arrays (the fields are the arrays im talking about). one holds the words, and one holds the corresponding hint
Programingwords(counter) = Strings.UCase(fields(0))
counter += 1
'this is where the hint is at
Programingwords(counter) = (fields(1))
counter += 1
End While
End Using
the error
ex.ToString()
"System.ArgumentException: Illegal characters in path.
at System.IO.Path.CheckInvalidPathChars(String path)
at System.IO.Path.NormalizePathFast(String path, Boolean fullCheck)
at System.IO.Path.NormalizePath(String path, Boolean fullCheck)
at System.IO.Path.GetFullPathInternal(String path)
at System.IO.Path.GetFullPath(String path)
at Microsoft.VisualBasic.FileIO.FileSystem.NormalizePath(String Path)
at Microsoft.VisualBasic.FileIO.TextFieldParser.ValidatePath(String path)
at Microsoft.VisualBasic.FileIO.TextFieldParser.InitializeFromPath(String path, Encoding defaultEncoding, Boolean detectEncoding)
at Microsoft.VisualBasic.FileIO.TextFieldParser..ctor(String path)
at HangMan.Form1.GetWords() in I:\vb\HangMan\HangMan\Form1.vb:line 274" String
The TextFieldParser constructor you use expects the name of a file. Instead, it gets the contents of the file. That goes Kaboom, the file content is not a valid path to a file. You'll need to the constructor that takes a Stream and use the StringReader class to provide the stream. For example:
Dim fields As String()
Dim delimiter As String = ","
Dim fileContent As String = My.Resources.ProggramingList
Dim stringStream as New System.IO.StringReader(fileContent)
Using parser As New TextFieldParser(stringStream)
REM etc...
End Using
This is a bit wasteful of memory but not an issue if the text is less than a megabyte or so. If it is more then you shouldn't put it in a resource.
When you debug this code, what is the value of the variable filename after you read it from My.Resources.GamesList? Is it a valid string, does it point to you're file?