find character and Insert a new line in the file - vb.net

I am looking to read a file line by line and once I reach a line that doesn't contain the same characters in columns 65 - 67 I want to insert a string line 2 lines above that. I am using VB.NET
So far I have written code that reads the file line by line.
I am unsure how to insert a string line to a file where characters in columns 65-67 are different
any help would be great. Thanks
Protected Sub UploadFile(sender As Object, e As EventArgs)
Dim fileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Dim filePath As String = Server.MapPath("~/Files/") & fileName
FileUpload1.SaveAs(filePath)
'--Read block of lines then insert line for each new block
For Each line In IO.File.ReadLines(filePath)
'If line.Substring(65, 3) <> " " Then '<> to previous substring
'--Insert new line
'End If
Next
End Sub
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" Text="Upload File" runat="server" OnClick="UploadFile" />

Something like this.
Dim lines As List(Of String) = IO.File.ReadLines(filePath).ToList
Dim idx As Integer = 0
Do While idx < lines.Count - 2
Dim thisLine As String = lines(idx)
Dim nextLine As String = lines(idx + 1)
If thisLine.Substring(65, 3) <> nextLine.Substring(65, 3) Then
lines.Insert(idx + 1, "NEW BLOCK")
idx += 1
End If
idx += 1
Loop
Dim foo As String = String.Join(ControlChars.Cr, lines)
IO.File.WriteAllText("path", foo)
edit - based on comments
Dim lines As List(Of String) = IO.File.ReadLines(filePath).ToList
Dim idx As Integer = 0
Do While idx < lines.Count - 2
Dim thisLine As String = lines(idx)
Dim nextLine As String = lines(idx + 1)
Dim key As String = thisLine.Substring(65, 3).Trim
If key <> nextLine.Substring(65, 3) AndAlso
key = "" Then
lines.Insert(idx + 1, "NEW BLOCK")
idx += 1
End If
idx += 1
Loop
Dim foo As String = String.Join(ControlChars.Cr, lines)
IO.File.WriteAllText("path", foo)

Related

Read the whole file into an array, replace one of the elements of that array, then write the whole file again. Text ends up the same

I have a form3 that when the user exits it attempts to save the time they spent playing. When trying to replace the line I end up with the exact same text, therefore nothing changes in the file. Why will it not replace the text? Thanks in advance.
File.AppendAllLines(Application.StartupPath + "\content\main\userdata\tgametime.txt", FileLines)
'this line will not write to file if it has the same file name because FileLines is still using it, if this could be solved too awesome!
Private Sub SaveGameTime()
Dim fullpath = Path.Combine(Application.StartupPath + "\content\main\userdata\gametime.txt")
Dim FileLines = File.ReadLines(fullpath)
Dim alltext = File.ReadAllText(fullpath)
Dim datalist = New List(Of String)
Dim line
datalist.Add(tbGameName.Text + " : " + LBtimeout.Text)
TextDiag(FileLines.Count.ToString, "Clear")
If FileLines.Count > 0 Then
If alltext.Contains(tbGameName.Text) Then
For Each line In FileLines
TextDiag(line, "Clear")
line.Replace(line, tbGameName.Text + " : " + LBtimeout.Text)
TextDiag("new line: " + line, "Clear")
Next
File.AppendAllLines(Application.StartupPath + "\content\main\userdata\tgametime.txt", FileLines)
Else
TextDiag("Line not found, adding new line", "Clear")
File.AppendAllLines(fullpath, datalist)
End If
Else
TextDiag("No lines not found, adding new line", "Clear")
File.AppendAllLines(fullpath, datalist)
End If
datalist.Clear()
fullpath = Nothing
FileLines = Nothing
datalist = Nothing
TextDiag Output
Got it working, replaces text at a specified string value in a file formatted like this: "Text > 0 : 0 : 0" . It gets a new time value extracted from a label formatted like this: "0 : 0 : 0", removes everything but the numbers and colons to this: "0:0:0", formats them to a TimeSpan and adds them to the outputlines which also contain any other original text.
Thank you
Dim fullpath = "yourpath"
Dim FileLines = File.ReadLines(fullpath)
Dim outputlines As New List(Of String)
Dim alltext = File.ReadAllText(fullpath)
Dim datalist = New List(Of String)
Dim line
Dim lbtime = TimeSpan.Parse(LBtimeout.Text.Replace(" ", ""))
datalist.Add("youstring" + " : " + "yourstring")
If FileLines.Count > 0 Then
If alltext.Contains("yourstring") Then
For Each line In FileLines
If line.contains("yourstring") Then
Dim liness = line.substring(line.indexof(">") + 1)
Dim linerep = liness.replace(" ", "")
Dim linetime = TimeSpan.Parse(linerep)
Dim timesum As TimeSpan = lbtime + linetime
line.replace(line, "")
line = "yourstring" + " > " + timesum.ToString
outputlines.Add(line)
Else
outputlines.Add(line)
End If
Next
File.WriteAllLines("yourpath", outputlines)
Else
File.AppendAllLines(fullpath, datalist)
End If
Else
'No lines not found, adding new line
File.AppendAllLines(fullpath, datalist)
End If
datalist.Clear()
fullpath = Nothing
FileLines = Nothing
datalist = Nothing

This code is supposed to output the number of times a word starts with a letter from the alphabet, but just displays zero for each one

This code is supposed to output the number of times a word starts with a letter from the alphabet, but just displays zero for each one
I get no errors, but just a text file with all of the letters and zero for each one.
When pressing the debug button, it appears to do nothing. Here's the code
Imports System.IO
Module Module1
Sub Main()
Dim myArray As New List(Of String)
Using myReader As StreamReader = New StreamReader(".\myFile.txt")
'telling VB that we're using a StreamREader, read a line at a time
Dim myLine As String
myLine = myReader.ReadLine 'assigns the line to String Variable myLine
Do While (Not myLine Is Nothing)
myArray.Add(myLine) 'adding it to the list of words in the array
Console.WriteLine(myLine)
myLine = myReader.ReadLine
Loop
End Using
SortMyArray(myArray) 'Calls the new SubRoutine => SortMyArray, passing through the parameter myArray,
'created back on line 7 that stores all of the lines read from the text file.
'Console.ReadLine()
wordCount(myArray)
End Sub
Sub SortMyArray(ByVal mySort As List(Of String))
Dim Tmp As String, writePath As String = ".\sorted.txt"
Dim max As Integer = mySort.Count - 1
Dim myWriter As StreamWriter = New StreamWriter(writePath)
For Loop1 = 0 To max - 1
For Loop2 = Loop1 + 1 To max
If mySort(Loop1) > mySort(Loop2) Then
Tmp = mySort(Loop2)
mySort(Loop2) = mySort(Loop1)
mySort(Loop1) = Tmp
End If
Next
myWriter.WriteLine(mySort.Item(Loop1).ToString())
Next
myWriter.Dispose()
End Sub
Sub wordCount(ByVal stringArray As List(Of String))
Dim alphabet As String = "abcdefghijklmnopqrstuvwxyz", myString As String
Dim writePath As String = ".\counted.txt"
Dim myWriter As StreamWriter = New StreamWriter(writePath)
Dim countOf(25) As Integer, Max As Integer = stringArray.Count - 1
For Loop1 = 0 To 25
myString = alphabet.Substring(Loop1, 1)
For Loop2 = 0 To Max
If stringArray(Loop2).Substring(0, 1) = myString Then
countOf(Loop1) += 1
End If
Next
myWriter.WriteLine(myString & " occured " & countOf(Loop1) & " times ")
Next
myWriter.Dispose()
End Sub
End Module
Any help would be appreciated. Thanks

Reading and writing from a csv file

Structure TownType
Dim Name As String
Dim County As String
Dim Population As Integer
Dim Area As Integer
End Structure
Sub Main()
Dim TownList As TownType
Dim FileName As String
Dim NumberOfRecords As Integer
FileName = "N:\2_7_towns(2).csv"
FileOpen(1, FileName, OpenMode.Random, , , Len(TownList))
NumberOfRecords = LOF(1) / Len(TownList)
Console.WriteLine(NumberOfRecords)
Console.ReadLine()
There are only 12 records in the file but this returns a value of 24 for number of records. How do I fix this?
Contents of csv file:
Town, County,Pop, Area
Berwick-upon-tweed, Nothumberland,12870,468
Bideford, devon,16262,430
Bognor Regis, West Sussex,62141,1635
Bridlington, East Yorkshire,33589,791
Bridport, Dorset,12977,425
Cleethorpes, Lincolnshire,31853,558
Colwyn bay, Conway,30269,953
Dover, Kent,34087,861
Falmouth, Cornwall,21635,543
Great Yarmouth, Norfolk,58032,1467
Hastings, East Sussex,85828,1998
This will read the contents into a collection and you can get the number of records from the collection.
Sub Main()
Dim FileName As String
Dim NumberOfRecords As Integer
FileName = "N:\2_7_towns(2).csv"
'read the lines into an array
Dim lines As String() = System.IO.File.ReadAllLines(FileName)
'read the array into a collection of town types
'this could also be done i a loop if you need better
'parsing or error handling
Dim TownList = From line In lines _
Let data = line.Split(",") _
Select New With {.Name = data(0), _
.County = data(1), _
.Population = data(2), _
.Area = data(3)}
NumberOfRecords = TownList.Count
Console.WriteLine(NumberOfRecords)
Console.ReadLine()
End Sub
Writing to the console would be accomplished with something like:
For Each town In TownList
Console.WriteLine(town.Name + "," + town.County)
Next
Many ways to do that
Test this:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
dim FileName as string = "N:\2_7_towns(2).csv"
Dim Str() As String = System.IO.File.ReadAllLines(filename)
'Str(0) contains : "Town, County,Pop, Area"
'Str(1) contains : "Berwick-upon-tweed, Nothumberland,12870,468"
'Str(2) contains : "Bideford, devon,16262,430"
' etc...
'Sample code for string searching :
Dim Lst As New List(Of String)
Lst.Add(Str(0))
Dim LookingFor As String = "th"
For Each Line As String In Str
If Line.Contains(LookingFor) Then Lst.Add(Line)
Next
Dim Result As String = ""
For Each St As String In Lst
Result &= St & Environment.NewLine
Next
MessageBox.Show(Result)
'Sample code creating a grid :
Dim Grid = New DataGridView
Me.Controls.Add(Grid)
Grid.ColumnCount = Str(0).Split(","c).GetUpperBound(0) + 1
Grid.RowCount = Lst.Count - 1
Grid.RowHeadersVisible = False
For r As Integer = 0 To Lst.Count - 1
If r = 0 Then
For i As Integer = 0 To Lst(r).Split(","c).GetUpperBound(0)
Grid.Columns(i).HeaderCell.Value = Lst(0).Split(","c)(i)
Next
Else
For i As Integer = 0 To Lst(r).Split(","c).GetUpperBound(0)
Grid(i, r - 1).Value = Lst(r).Split(","c)(i)
Next
End If
Next
Grid.AutoResizeColumns()
Grid.AutoSize = True
End Sub

creating csv file in VB2010

I am trying to create CSV file for below code. When i run the code initially it usually create the csv file. For same code it not creating CSV file. Let me Know What issue is
If counter = 1 Then
counter = 0
Dim headerText = ""
Dim csvFile As String = IO.Path.Combine(My.Application.Info.DirectoryPath, "test.csv")
If Not IO.File.Exists((csvFile)) Then
headerText = "Date,TIME ,Current, "
End If
Using outFile = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
If headerText.Length > 0 Then
outFile.WriteLine(headerText)
End If
Dim date1 As String = "24-10-2014"
Dim time1 As String = CStr(TimeOfDay())
Dim Current As String = CStr(distance)
'Dim x As String = CStr(CDbl(date1 + "," + time1 + ",") + distance)
Dim x As String = date1
outFile.Write(x)
End Using
End If

How can I get String values rather than integer

How To get StartString And EndString
Dim startNumber As Integer
Dim endNumber As Integer
Dim i As Integer
startNumber = 1
endNumber = 4
For i = startNumber To endNumber
MsgBox(i)
Next i
Output: 1,2,3,4
I want mo make this like sample: startString AAA endString AAD
and the output is AAA, AAB, AAC, AAD
This is a simple function that should be easy to understand and use. Every time you call it, it just increments the string by one value. Just be careful to check the values in the text boxes or you can have an endless loop on your hands.
Function AddOneChar(Str As String) As String
AddOneChar = ""
Str = StrReverse(Str)
Dim CharSet As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim Done As Boolean = False
For Each Ltr In Str
If Not Done Then
If InStr(CharSet, Ltr) = CharSet.Length Then
Ltr = CharSet(0)
Else
Ltr = CharSet(InStr(CharSet, Ltr))
Done = True
End If
End If
AddOneChar = Ltr & AddOneChar
Next
If Not Done Then
AddOneChar = CharSet(0) & AddOneChar
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim S = TextBox1.Text
Do Until S = TextBox2.Text
S = AddOneChar(S)
MsgBox(S)
Loop
End Sub
This works as a way to all the codes given an arbitrary alphabet:
Public Function Generate(starting As String, ending As String, alphabet As String) As IEnumerable(Of String)
Dim increment As Func(Of String, String) = _
Function(x)
Dim f As Func(Of IEnumerable(Of Char), IEnumerable(Of Char)) = Nothing
f = _
Function(cs)
If cs.Any() Then
Dim first = cs.First()
Dim rest = cs.Skip(1)
If first = alphabet.Last() Then
rest = f(rest)
first = alphabet(0)
Else
first = alphabet(alphabet.IndexOf(first) + 1)
End If
Return Enumerable.Repeat(first, 1).Concat(rest)
Else
Return Enumerable.Empty(Of Char)()
End If
End Function
Return New String(f(x.ToCharArray().Reverse()).Reverse().ToArray())
End Function
Dim results = New List(Of String)
Dim text = starting
While True
results.Add(text)
If text = ending Then
Exit While
End If
text = increment(text)
End While
Return results
End Function
I used it like this to produce the required result:
Dim alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim results = Generate("S30AB", "S30B1", alphabet)
This gave me 63 values:
S30AB
S30AC
...
S30BY
S30BZ
S30B0
S30B1
It should now be very easy to modify the alphabet as needed and to use the results.
One option would be to put those String values into an array and then use i as an index into that array to get one element each iteration. If you do that though, keep in mind that array indexes start at 0.
You can also use a For Each loop to access each element of the array without the need for an index.
if the default first two string value of your output is AA.
You can have a case or if-else conditioning statement :
and then set 1 == A 2 == B...
the just add or concatenate your default two string and result string of your case.
I have tried to understand that you are looking for a series using range between 2 textboxes. Here is the code which will take the series and will give the output as required.
Dim startingStr As String = Mid(TextBox1.Text, TextBox1.Text.Length, 1)
Dim endStr As String = Mid(TextBox2.Text, TextBox2.Text.Length, 1)
Dim outputstr As String = String.Empty
Dim startNumber As Integer
Dim endNumber As Integer
startNumber = Asc(startingStr)
endNumber = Asc(endStr)
Dim TempStr As String = Mid(TextBox1.Text, 1, TextBox1.Text.Length - 1)
Dim i As Integer
For i = startNumber To endNumber
outputstr = outputstr + ", " + TempStr + Chr(i)
Next i
MsgBox(outputstr)
The First two lines will take out the Last Character of the String in the text box.
So in your case it will get A and D respectively
Then outputstr to create the series which we will use in the loop
StartNumber and EndNumber will be give the Ascii values for the character we fetched.
TempStr to Store the string which is left off of the series string like in our case AAA - AAD Tempstr will have AA
then the simple loop to get all the items fixed and show
in your case to achive goal you may do something like this
Dim S() As String = {"AAA", "AAB", "AAC", "AAD"}
For Each el In S
MsgBox(el.ToString)
Next
FIX FOR PREVIOUS ISSUE
Dim s1 As String = "AAA"
Dim s2 As String = "AAZ"
Dim Last As String = s1.Last
Dim LastS2 As String = s2.Last
Dim StartBase As String = s1.Substring(0, 2)
Dim result As String = String.Empty
For I As Integer = Asc(s1.Last) To Asc(s2.Last)
Dim zz As String = StartBase & Chr(I)
result += zz & vbCrLf
zz = Nothing
MsgBox(result)
Next
**UPDATE CODE VERSION**
Dim BARCODEBASE As String = "SBA0021"
Dim BarCode1 As String = "SBA0021AA1"
Dim BarCode2 As String = "SBA0021CD9"
'return AA1
Dim FirstBarCodeSuffix As String = Replace(BarCode1, BARCODEBASE, "")
'return CD9
Dim SecondBarCodeSuffix As String = Replace(BarCode2, BARCODEBASE, "")
Dim InternalSecondBarCodeSuffix = SecondBarCodeSuffix.Substring(1, 1)
Dim IsTaskCompleted As Boolean = False
For First As Integer = Asc(FirstBarCodeSuffix.First) To Asc(SecondBarCodeSuffix)
If IsTaskCompleted = True Then Exit For
For Second As Integer = Asc(FirstBarCodeSuffix.First) To Asc(InternalSecondBarCodeSuffix)
For Third As Integer = 1 To 9
Dim tmp = Chr(First) & Chr(Second) & Third
Console.WriteLine(BARCODEBASE & tmp)
If tmp = SecondBarCodeSuffix Then
IsTaskCompleted = True
End If
Next
Next
Next
Console.WriteLine("Completed")
Console.Read()
Take a look into this check it and let me know if it can help