Dim sr as new IO.streamreader(xxx.txt)
Dim sw as new IO.streamwriter(xxxx.txt)
Dim s as string = sr.readtoend
dim ssss as string
dim i as integer
while not sr.endofstream
for i = 0 to 10
ssss = "hello" & listbox.items(i)
s = replace(s,"[[abc]]",ssss)
Call sw.writeline(s)
Next
End while
call sw.close()
I was trying to replace the string [[abc]] in a .txt file called xxx with ssss and then write it into another .txt named xxxx. The problem is that ssss is changing all the time and when I debug the program it says s is "Nothing". I need all ssss values in the new txt. So I wonder maybe "Replace" is not suitable in this case? Any ideas on how to fix this issue? BTW, I am using vb in vs 2012, not vb 6.0. Thanks.
It seems you are having errors with null. Try to catch whenever "s" is nothing, then if it is, skip it. Otherwise do the Replace.
Check it with something like
if s <> nothing then
s = s.replace(s,"[[abc]]",ssss)
Call sw.writeline(s)
next
Related
I have tried using the solution (given below) for the "Read and Write to specific line in textfile with VB.Net" problem asked 4 years ago
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
But each time I encounter the following error:
The process cannot access the file 'file_path' because it is being
used by another process.
Any idea as to why this happens?
Your code works OK for me. System.IO.File.ReadAllLines() is supposed to close the file afterwards.
Maybe something else is preventing write access to the file. (Some application you're using to see if it's working?!) To check that, replace
Dim lines() As String = System.IO.File.ReadAllLines(filePath)
with
Dim lines() As String = {"0","1","2","3","ORIGIN 4", "5"}
and see if it still fails.
I have a program that needs to look through a text file line by line, the lines look like this:
10-19-2015 Brett Reinhard All Bike Yoga Run the Studio Design Your Own Strength
These are separated by tabs in the text file.
What I want to do is look at the second value, in this case "Brett Reinhard" and move the full line to another textfile called "Brett Reinhard"
I was thinking of using an array to check to see if the second 'column' in the line matched any value within a given array, if it does I want to perform a specific action.
The way I am thinking of doing this is with a For/next statement, now while it will work it will be a laborious process for the computer that I will be using it on.
The code I am thinking of using looks like this:
For intCounter=0 to Whatever Number is the last number of the array
If currentfield.contains(array(intCounter)) Then
Open StreamWriter(File directory & array(intcounter) & ".txt")
Streamwriter.Writeline(currentfield)
End IF
Is there a better way of doing this, such as referencing the second 'column' in the line, similar to the syntax used in VBA for excel.
Name=Cells(1,2).Value
If you can guarantee that a line will only use the tab characters as field separators, you can do something along this:
Open the stream for reading text
Open a stream for writing text
Read a line of text
Use the Split method to break the incoming line into an array of fields
If the second element in the array is your sentinel value, write the original line to the writer
Repeat yourself until you have reached the end of file (ReadLine will return Nothing, or null for those c# folk).
Close and dispose of your stream objects.
If you aren't sure of the format, you will want to take the hit and use the TextFieldParser as mentioned in an earlier comment.
So while its not using an array to search a file, what I ended up doing works just as well. I ended up using the split method thanks to #Martin Soles.
Here is what I came up with:
Sub Main()
Dim intCount As Integer = 1
Dim words As String
Dim split As String()
Using MyReader As New Microsoft.VisualBasic.
FileIO.TextFieldParser(
"I:\Games, Events, & Promotions\FRP\Back End\Approved.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
words = currentField
split = words.Split(New [Char]() {CChar(vbTab)})
For Each s As String In split
If intCount = 2 Then
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("I:\Games, Events, & Promotions\FRP\Back End\" & s & ".txt", True)
file.WriteLine(currentField)
file.Close()
End If
intCount = intCount + 1
Next s
intCount = 1
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
End Using
End Sub 'Main
Thank you guys for the suggestions.
For right now the split method will work for what is needed.
I am currently trying to manipulate a line in a file that we are using to retain data, using comma delimiters. For example -
121,1212, XJAY,Sean K,Kean S,AAAA-BBBB-AAAA-BBBB-AAAA
12456,987654,WYST,Steve Jobs,Bill Gates,CAAA-BBBB-AAAA-BBBB-AAAA
If I assume that the last line is always a unique code, is it possible to identify that line in the text file and append it with another field?
Prior research has been reading through the APIs for StreamReader and StreamWriter, and looking through other StackOverflow questions, however most questions seem focused on just appending to the end of the file, or in different languages!
As always thank you for your time, and if there is anything I've left off please let me know!
You can't manipulate a line in a file in any reasonably easy way.
There are no methods to work with lines in a file, because files are not line based. They are not even character based. The bytes in the file are decoded into characters, then the line break characters are recognised and the characters can be split into lines.
The easiest way to manipulate a line is to read the entire file into a string array, change the string that you want change, then write the entire string array to the file.
Example:
Dim fileName As String = "c:\data.txt"
Dim lines As String() = File.ReadAllLines(fileName)
For i As Integer = 0 To lines.Length - 1
Dim line As String = lines(i)
If line.StartsWith("12456,") Then
lines(i) = line & ",More data"
End If
Next
File.WriteAllLines(fileName, lines)
If you are looking for a way to parse Each line with StreamReader and StreamWriter: Here it is:
'You will need Imports System.IO
Dim TheNewFile As String
Dim MyLine As String
Dim MyStream2 As New FileStream("C:\Your Directory\YourFile.txt", FileMode.Open)
Dim MyReader As New StreamReader(MyStream2)
Dim MySettings As New StringReader(MyReader.ReadToEnd)
MyReader.BaseStream.Seek(0, SeekOrigin.Begin)
MyReader.Close()
MyStream2.Close()
Try
Do
MyLine = MySettings.ReadLine
'This if statement is an exit parameter. It can be if it contains or if 5 consecutive lines are nothing. It could be a number of things
If MyLine Is Nothing Then Exit Do
'This is the file you will write. You could do if MyLine = "Test" Then ........... append whatever and however you need to
TheNewFile = TheNewFile & MyLine & vbCrLf
Loop
Catch ex As Exception
MsgBox(ex.ToString())
End Try
'-----------------Write The new file!!!----------------
Dim MyStream3 As New FileStream("C:\Where you want to write New File\NewFileName.txt", FileMode.Create)
Dim MyWriter3 As New StreamWriter(MyStream3)
MyWriter3.Write(TheNewFile & "Test")
MyWriter3.Close()
MyStream3.Close()
I simply need to read lines from a text file and show them. When I run this I can see that id does what I want, but after it reads the last value it just shows a blank form on my screen and does not move on. It seems like it can't find the end of the file or something. I don't get an error.
Using sr As New System.IO.StreamReader(Application.StartupPath & "\myfile.cfg")
Dim Line As String = ""
Dim i As Integer = 0
Dim temp_array As Array
Do While Line IsNot Nothing
Line = sr.ReadLine
temp_array = Line.Split("=")
'MessageBox.Show(temp_array(0))
Loop
End Using
That is bad code because you're actually going to use Line before testing whether it's Nothing. Here are two good options for looping through the lines of a text file:
Using reader As New StreamReader(filePath)
Dim line As String
Do Until reader.EndOfStream
line = reader.ReadLine()
'...
Loop
End Using
For Each line In File.ReadLines(filePath)
'...
Next
As you can see, the second is far more concise but it does require .NET 4.0 or later.
I keep getting window that pops up when I run a VB.NET console program I made that simply says "Object reference not set to an instance of an object." The window doesn't even say "error" or anything--the title is simply the name of the project. However...I'm assuming this is something I don't want.
I searched around a bit and found posts about similar messages but couldn't figure out how they applied to my situation.
Here is some of my code. (This program is supposed to take some data from a preformatted text file that describes the geometry of a cross section of a river and systematically enters some new geometric data to represent the riverbed being cleaned/cleared out in a certain way, and then write the new data to a new file in a similar format.)
Imports System
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Module module1
Public Sub Main()
Using sr As New StreamReader("C:\inputfile.txt")
Using outfile As New StreamWriter("C:\outputfile.txt")
Dim line As String = ""
Dim styles As Globalization.NumberStyles
styles = Globalization.NumberStyles.AllowLeadingSign Or Globalization.NumberStyles.AllowDecimalPoint
Dim stations(-1) As Double
Dim elevations(-1) As Double
Dim i As Integer = 0
Do
Try
line = sr.ReadLine()
Dim stringarray() As String = line.Split()
ReDim Preserve stations(i)
ReDim Preserve elevations(i)
stations(i) = Double.Parse(stringarray(0), styles)
elevations(i) = Double.Parse(stringarray(1), styles)
Catch ex As Exception
MsgBox(ex.Message)
End Try
i = i + 1
Loop Until line Is Nothing
Dim min As Double = elevations(0)
(some more code.....)
End Using
End Using
End Sub
End Module
I only included the first part of my code because when I put a break at the "Loop Until line Is Nothing" statement, the message didn't come up until after I went through the break, but when I put the break at the "Dim min As Double = elevations(0)" statement, the message came up before the program got to the break.
I don't really get what's wrong with my code. Anyone have any ideas?
Thanks!
See if this works any better:
Public Sub Main()
Dim styles As Globalization.NumberStyles = Globalization.NumberStyles.AllowLeadingSign Or Globalization.NumberStyles.AllowDecimalPoint
Dim stations As New List(Of Double)
Dim elevations As New List(Of Double)
For Each line As String in File.ReadLines("C:\inputfile.txt")
Try
Dim stringarray() As String = line.Split()
stations.Add(Double.Parse(stringarray(0), styles))
elevations.Add(Double.Parse(stringarray(1), styles))
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next Line
Dim min As Double = elevations(0)
Using outfile As New StreamWriter("C:\outputfile.txt")
End Using
End Sub
Note that I moved your output file to the end... you haven't written anything yet, and so it's a good idea to wait as long as possible to open it, to keep it open for as short a time as possible.
The code fails after the last line has been read because the exit condition (Loop Until) doesn't know that you have reached the end of file. So another loop is started and the code tries to read an inexistent line. The last ReadLine returns Nothing, but the code tries to split it.
You could add a check before trying to split the line and jump directly to the Loop Until statement if you don't have anymore lines to read. Of course I also suggest to remove the array redim at every loop and use a more flexible List(Of Double)
Dim stations = New List(Of Double)
Dim elevations = New List(Of Double)
Do
Try
' After the last line this command returns null (Nothing in VB)
line = sr.ReadLine()
if line IsNot Nothing Then
Dim stringarray() As String = line.Split()
stations.Add(Double.Parse(stringarray(0), styles))
elevations.Add(Double.Parse(stringarray(1), styles))
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Loop Until line Is Nothing
OK...I feel really dumb now...after reading through all of your answers and looking at Steve's code, I realized my code was going through the loop one last time where "line" was set as nothing at the beginning of the loop and it was still trying to add "nothing" as an element to the arrays. The key to fixing it was adding an "If line IsNot Nothing" statement before the statements adding elements to the arrays, which Steve had.
Thank you all for your answers!