Read a text file in VB - vb.net

New Visual basic programmer here. Trying to get a textfile to be read by the program but it seems to simply not work, no error messages or anything. It just does not grab the values at all
The textfile name is exactly the same.
Public Sub ReadDef()
Dim DefSR As IO.StreamReader = IO.File.OpenText("BikeDefault.txt")
GlobalTotBikes = DefSR.ReadLine()
GlobalRentRate = DefSR.ReadLine()
GlobalHSTRate = DefSR.ReadLine()
GlobalTourRate = DefSR.ReadLine()
GlobalGPSRate = DefSR.ReadLine()
GlobalInsurRate = DefSR.ReadLine()
GlobalWaterBotRate = DefSR.ReadLine()
GlobalNextBookNum = DefSR.ReadLine()
GlobalNextCustNum = DefSR.ReadLine()
GlobalNextInvoiceNum = DefSR.ReadLine()
DefSR.Close()
End Sub
I've compared this code a bunch of times to the example I was given and I see nothing different.
Thanks.

Simple search on google http://www.dotnetperls.com/streamreader-vbnet
Make 100% sure BikeDefault.txt exists. If you wish to make sure, copy the file over to the C:\ Drive to keep it simple and replace your BikeDefault.txt with "C:\\BikeDefault.txt"
You can use the StreamReader like so:
Imports System.IO
Module Module1
Sub Main()
' Store the line in this String.
Dim line As String
Dim FilePath As String = "C:\\BikeDefault.txt"
' Create new StreamReader instance with Using block.
Using reader As StreamReader = New StreamReader(FilePath)
' Read one line from file
line = reader.ReadLine
End Using
' Write the line we read from "file.txt"
Console.WriteLine(line)
End Sub
End Module
Or keep it simple with File.ReadAllLines.
For Each line As String In File.ReadLines("MyTextFile.txt")
'Code here to read each line
Next line

I use
IO.File.ReadAllText("BikeDefault.txt")

Related

How to loop when using FileSystem.input?

I'm migrating a program from vb6 to vb.net.
I have a file with multiple lines to read from.
My code:
FileOpen(1,FileName,OpenMode.Input)
Do until EOF(1)
FileSystem.Input( 1 , param1, param2, param3)
Loop
My problem with this code is that the loop isn't "looping"...
Its reading the same line over and over.
When using :
Do until FileSystem.EOF(1)
strData = Filesystem.LineInput(1)
Loop
The loop works fine.
But I can't use it because I have different params for each line, which is inconsistent.
What is the problem? Why isn't it looping for the first time?
Are there other approaches for tackling this problem?
Are there other approaches for this kind of code?
Read all the lines of a text file into an array all in memory in one go (assuming it's a text file because you said "multiple lines"):
Dim arr = System.IO.File.ReadAllLines("path here")
'loop over the array
For Each line as String in arr
'... process the line
Next line
To read a file incrementally, line by line, if it's huge and you don't want to load it all into memory, use ReadLines instead of ReadAllLines:
For Each line as String in System.IO.File.ReadLines("path here")
'... process the line
Next line
Another example:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim line As String
Dim values() As String
Dim FileName As String = "c:\someFile.txt"
Using sr As New StreamReader(FileName)
While Not sr.EndOfStream
line = sr.ReadLine()
values = line.Split(",")
End While
End Using
End Sub
End Class
If you show us some sample lines from your file we could give more detailed answers.

Writing/Reading from text files in VB.net

I am a student in computer science and for a project I need to be able to read from a text file in a way that each line is assigned to a space within an array. This should happen so that each line of text file is read in the order that it appears in the text file. I would also appreciate any methods of writing to a text file as well.
If this question is already explained, could you please direct me to the existing answer.
Things to note:
1) I am coding in a console application in VB.NET
2) I am relatively new at coding
You can do it like this:
Dim sFile As String = "D:\File.txt"
Dim aLines As String() = System.IO.File.ReadAllLines(sFile)
System.IO.File.WriteAllLines(sFile, aLines)
Here's a sample from the official documentation:
Imports System.IO
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
Dim sw As StreamWriter
' This text is added only once to the file.
If File.Exists(path) = False Then
' Create a file to write to.
Dim createText() As String = {"Hello", "And", "Welcome"}
File.WriteAllLines(path, createText)
End If
' This text is always added, making the file longer over time
' if it is not deleted.
Dim appendText As String = "This is extra text" + Environment.NewLine
File.AppendAllText(path, appendText)
' Open the file to read from.
Dim readText() As String = File.ReadAllLines(path)
Dim s As String
For Each s In readText
Console.WriteLine(s)
Next
End Sub
End Class
Remarks
This method opens a file, reads each line of the file, then adds each line as an element of a string array. It then closes the file. A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed. The resulting string does not contain the terminating carriage return and/or line feed.
Module Module1
Sub Main()
'Declare four variables
Dim oReader As New System.IO.StreamReader(".\archive01.txt") 'This file has to exist in the aplication current directory.
Dim oWriter As New System.IO.StreamWriter(".\archive02.txt") 'This file will be created by the software.
Dim oArray() As String = {}
Dim oString As String = Nothing
'For reading from .\archive01.txt and to load in oArray().
oString = oReader.ReadLine
While Not oString Is Nothing
If UBound(oArray) = -1 Then 'Ubound = Upper Bound, also exist LBound = Lower Bound.
ReDim oArray(UBound(oArray) + 1)
Else
ReDim Preserve oArray(UBound(oArray) + 1)
End If
oArray(UBound(oArray)) = New String(oString)
oString = oReader.ReadLine
End While
oReader.Close()
'For writing from oArray() to .\archive02.txt.
For i = 0 To oArray.Count - 1 Step 1
oWriter.WriteLine(oArray(i))
Next
oWriter.Close()
End Sub
End Module
Hi, try with this code. It works well. I hope that this helps to you to learn how to do this kind of things. Thank you very much. And happy codding!. :)

Writing Part/Block of File to another File

Please Help: I would like to read one block from file inPath and write to another file outPath.
I am using ReadLines method to read the File line by line and when reach at START_BLOCK, start writing to the output file and continue until you find the END_BLOCK.
I know couple of other methods by copying the whole file into a variable and pick the block what I need. I can't use saving on a variable as my files are very big GB+
The coding I have below copies the line at the "START_BLOCK" Can't really figure it out how to continue writing until the "END_BLOCK". Please suggest and thank you very much in advance.
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If line.Contains("START_BLOCK") Then
sw.WriteLine(line)
'-------HOW DO I CONTINUE TO WRITE UNTIL "END_BLOCK"
End If
Next line
End Using
You could just set a flag to indicate that you are inside of the block, and use that to write out the lines until you find the end tag, e.g. something like this (untested code!):
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Dim insideBlock As Boolean = False
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If line.Contains("START_BLOCK") Then
sw.WriteLine(line)
insideBlock = True
ElseIf line.Contains("END_BLOCK") Then
sw.WriteLine(line)
insideBlock = False
Exit For
ElseIf insideBlock Then
sw.WriteLine(line)
End If
Next line
End Using
UPDATE
Since the comments are getting out of control - here's a version to handle multiple blocks with different start tags but the same end tag (untested since I'm at home on my Mac):
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Dim insideBlock As Boolean = False
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If IsStartOfBlock(line) Then
sw.WriteLine(line)
insideBlock = True
ElseIf line.Contains("END_BLOCK") Then
sw.WriteLine(line)
insideBlock = False
ElseIf insideBlock Then
sw.WriteLine(line)
End If
Next line
End Using
'...
' Logic to determine if the line is the start of a block, for example:
Private Function IsStartOfBlock(line As String) As Boolean
Dim startMarkers() As String = {
"START_BLOCK", "START_BLOCK2", "START_BLOCKX"
}
Return startMarkers.Any(Function(x) line.Contains(x))
End Function
The loop will exit at the end of file anyway, so the last block should be ok too.

How can download file from FTP server with some extension in VisualBasic

I want to download the some file on remote location from FTP protocol, that have any extentions. For example I want to download the all file from remote site *.pdf, *.txt . So I have build this code in Visual Basic.
Public Function GetFiles() As Generic.List(Of String)
Dim fileList As New Generic.List(Of String)
Select Case _config.Protocol
Case FTPConfiguration.FTPProtocol.FTP
Dim objFTPRequest As FtpWebRequest = CType(FtpWebRequest.Create(New Uri(_config.FTPUrl & _config.MonitorDirectory)), FtpWebRequest)
objFTPRequest.Credentials = New NetworkCredential(_config.FTPUsername, _config.FTPPassword)
objFTPRequest.KeepAlive = False
objFTPRequest.UsePassive = False
objFTPRequest.UseBinary = True
objFTPRequest.Method = WebRequestMethods.Ftp.ListDirectory
Dim response As FtpWebResponse = CType(objFTPRequest.GetResponse(), FtpWebResponse)
Using respStream As StreamReader = New StreamReader(objFTPRequest.GetResponse().GetResponseStream())
Dim line As String = respStream.ReadLine()
While line IsNot Nothing
If line Like _config.FileSearch Then
fileList.Add(line)
End If
line = respStream.ReadLine()
End While
End Using
End Select
For Each fileName As String In fileList
Me.DownloadFile(fileName)
Next
Return fileList
End Function
How you can see, I have write this line to find the File but not works:
If line Like _config.FileSearch Then
I use LIKE operator but I think that this is not the corret way to fixed my problem.
You could use line.EndsWith(".pdf") to check if the file ends with that extension.
If you want to use like, the _config.FileSearch must be "*.pdf".
If line Like "*.pdf" Then
Console.WriteLine(line)
End If
You can also use Regular Expressions.
If Regex.IsMatch(line, "^.*\.(pdf|doc|txt|zip)$", RegexOptions.IgnoreCase) Then
Console.WriteLine(line)
End If
Refer String.EndsWith and Like

Separating large file and inserting carriage returns based on string

New to VB.Net but a friend recommended that I used it for what I'm trying to do. I have a huge text file and I want to insert carriage returns in after a specific string.
Apart from the mess I have below , how would I alter this to read a file and then once we see the text "ext" insert a new line feed. I'm expecting one of the lines in the input file to produce alot of carriage returns.
Currently what I have managed to mock together below reads an input file until end of line and writes it out again into another file.
Module Module1
Sub Main()
Try
' Create an instance of StreamReader to read from a file.
' The using statement also closes the StreamReader.
Using sr As StreamReader = New StreamReader("C:\My Documents\input.txt")
Dim line As String
' Read and display lines from the file until the end of
' the file is reached.
Using sw As StreamWriter = New StreamWriter("C:\My Documents\output.txt")
Do Until sr.EndOfStream
line = sr.ReadLine()
sw.WriteLine(line)
Console.WriteLine("done")
Loop
End Using
End Using
Catch e As Exception
' Let the user know what went wrong.
Console.WriteLine("The file could not be read:")
Console.WriteLine(e.Message)
End Try
Console.ReadKey()
End Sub
Changes made following comments.. Falling over at 500mb files due to memory constraints:
Sub Main()
Try
' Create an instance of StreamReader to read from a file.
' The using statement also closes the StreamReader.
Using sr As StreamReader = New StreamReader("C:\My Documents\input.txt")
Dim line As String
Dim term As String = "</ext>"
' Read and display lines from the file until the end of
' the file is reached.
Using sw As StreamWriter = New StreamWriter("C:\My Documents\output.txt")
Do Until sr.EndOfStream
line = sr.ReadLine()
line = line.Replace(term, term + Environment.NewLine)
sw.WriteLine(line)
Console.WriteLine("done")
Loop
End Using
End Using
Since your lines are very big, you'll have to:
Read/Write one character at a time
Save the last x characters
If the last x characters are equal to your term, write a new line
Dim term As String = "</ext>"
Dim lastChars As String = "".PadRight(term.Length)
Using sw As StreamWriter = New StreamWriter("C:\My Documents\output.txt")
Using sr As New System.IO.StreamReader("C:\My Documents\input.txt")
While Not sr.EndOfStream
Dim buffer(1) As Char
sr.Read(buffer, 0, 1)
lastChars &= buffer(0)
lastChars = lastChars.Remove(0, 1)
sw.Write(buffer(0))
If lastChars = term Then
sw.Write(Environment.NewLine)
End If
End While
End Using
End Using
Note: This will not work with a Unicode file. This assume each characters are one byte.