vb.net readalllines fill form replace certain lines coding advice - vb.net

What I'm trying to accomplish is reading a text file and selecting certain lines to modify by filling in text from a second form. Here is an example the code I'm currently using. What's happening is I'm looking for a line that starts with 718 and then somewhere after that line there will be a line that starts with 720. I need both lines to fill in the second form. The only way I can think of is to just keep adding 1 to the line until it reaches the line I need. I'm still new to this and I'm sure there's an easier way to do this maybe using Try or While but I'm not sure how. Appreciate any help.
Dim lines() As String = File.ReadAllLines(tempsave)
For i As Integer = 0 To lines.Length - 1
If lines(i).StartsWith("718") Then
If lines(i + 1).StartsWith("720") Then
Dim array() As String = lines(i).Split("*"c, "~"c)
Dim array2() As String = lines(i + 1).Split("*"c, "~"c)
FormFill.TextBox1.Text = array(3)
FormFill.TextBox2.Text = array(9)
FormFill.ShowDialog()
lines(i) = lines(i).Replace(array(3), FormFill.TextBox1.Text)
lines(i + 1) = lines(i + 1).Replace(array(9), FormFill.TextBox2.Text)
Else
If lines(i + 2).StartsWith("720") Then
Dim array() As String = lines(i).Split("*"c, "~"c)
Dim array2() As String = lines(i + 2).Split("*"c, "~"c)
FormFill.TextBox1.Text = array(3)
FormFill.TextBox2.Text = array(9)
FormFill.ShowDialog()
lines(i) = lines(i).Replace(array2(3),FormFill.TextBox1.Text)
lines(i + 2) = lines(i + 2).Replace(array(9), FormFill.TextBox2.Text)
End If
End If
End If
Next
Example Data:
Input:
123*test*test*test~
718*test*test*test~
543*test*test*test~
720*test*test*test~
Output:
123*test*test*test~
718*test*test*newdata~
543*test*test*test~
720*test*test*newdata~

Here, try this:
Public Sub Lines()
Dim _
aNextLines,
aAllLines As String()
Dim _
s718Line,
s720Line As String
aAllLines = IO.File.ReadAllLines("D:\Logs\Data.log")
For i As Integer = 0 To aAllLines.Length - 1
If aAllLines(i).StartsWith("718") Then
s718Line = aAllLines(i)
aNextLines = aAllLines.Skip(i + 1).ToArray
s720Line = aNextLines.FirstOrDefault(Function(Line) Line.StartsWith("720"))
' Process data here
End If
Next
End Sub
--UPDATE--
Here's a modified version that both reads and writes:
Public Sub Lines()
Dim oForm As FormFill
Dim _
aNextLines,
aAllLines As String()
Dim _
i718Index,
i720Index As Integer
Dim _
s718Line,
s720Line As String
oForm = New FormFill
aAllLines = IO.File.ReadAllLines(oForm.FilePath)
s718Line = String.Empty
s720Line = String.Empty
For i718Index = 0 To aAllLines.Length - 1
If aAllLines(i718Index).StartsWith("718") Then
s718Line = aAllLines(i718Index)
aNextLines = aAllLines.Skip(i718Index + 1).ToArray
For i720Index = 0 To aNextLines.Length - 1
If aNextLines(i720Index).StartsWith("720") Then
s720Line = aNextLines(i720Index)
Exit For ' Assumes only one 720 line in the file
End If
Next
Exit For ' Assumes only one 718 line in the file
End If
Next
oForm.TextBox718.Text = s718Line
oForm.TextBox720.Text = s720Line
oForm.TextBox718.Tag = i718Index
oForm.TextBox720.Tag = i720Index
End Sub
Now, in your Save button's Click event handler:
Private Sub SaveButton_Click(Sender As Button, e As EventArgs) Handles SaveButton.Click
Dim aAllLines As String()
Dim _
i718Index,
i720Index As Integer
Dim _
s718Line,
s720Line As String
s718Line = Me.TextBox718.Text
s720Line = Me.TextBox720.Text
i718Index = Me.TextBox718.Tag
i720Index = Me.TextBox720.Tag
aAllLines = IO.File.ReadAllLines(Me.FilePath)
aAllLines(i718Index) = s718Line
aAllLines(i720Index) = s720Line
IO.File.WriteAllLines(Me.FilePath, aAllLines)
End Sub
That should do it.

Related

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

system.io.ioexception the process cannot access because it is being used by another process

i am getting this problem in some systems, some systems working properly, here my code is,
Dim fileName As String = "FaultTypesByMonth.csv"
Using writer As IO.StreamWriter = New IO.StreamWriter(fileName, True, System.Text.Encoding.Default) '------------ rao new ----
Dim Str As String
Dim i As Integer
Dim j As Integer
Dim headertext1(rsTerms.Columns.Count) As String
Dim k As Integer = 0
Dim arrcols As String = Nothing
For Each column As DataColumn In TempTab.Columns
arrcols += column.ColumnName.ToString() + ","c
k += 1
Next
writer.WriteLine(arrcols)
For i = 0 To (TempTab.Rows.Count - 1)
For j = 0 To (TempTab.Columns.Count - 1)
If j = (TempTab.Columns.Count - 1) Then
Str = (TempTab.Rows(i)(j).ToString)
Else
Str = (TempTab.Rows(i)(j).ToString & ",")
End If
writer.Write(Str)
Next
writer.WriteLine()
Next
writer.Close()
writer.Dispose()
End Using
Dim FileToDelete As String = Nothing
Dim sd As New SaveFileDialog
sd.Filter = "CSV Files (*.csv)|*.csv"
sd.FileName = "FaultTypesByMonth"
If sd.ShowDialog = Windows.Forms.DialogResult.OK Then
FileCopy(fileName, sd.FileName)
MsgBox(" File Saved in selected path")
FileToDelete = fileName
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
End If
FileToDelete = fileName
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
End If
when i am trying to save this file in desired path, then i am getting this error.
if save in shared folder i am not getting this error
system.io.ioexception the process cannot access because it is being used by another process...
what i am doing wrong,Help me

More efficient method for string parsing?

First part of the code is to retrieve data from the web. It takes only a part of the second to complete the request. Second part of the code is to split data so that parts of data can be shown in different labels and it takes around 5-6 second to complete this operation?
Why is that? Can it be done faster?
First part of the code (textbox1 key down event)
If e.KeyCode = Keys.Enter Then
TextBox1.Text = UCase(TextBox1.Text)
If TextBox1.Text = "" Then
GoTo exx
Else
Dim strURL As String
Dim strSymbol As String = TextBox1.Text
strURL = " http://quote.yahoo.com/d/quotes.csv?" & _
"s=" & strSymbol & _
"&d=t" & _
"&f=snl1pmwvj1l1"
MessageBox.Show(RequestWebData(strURL))
Second part of the code and functions :
Label24.Text = (GetName2(RequestWebData(strURL), 3))
Dim myText = Label24.Text
Dim dIndex = myText.IndexOf("Inc.")
If (dIndex > -1) Then
Label24.Text = (Strings.Left(Label24.Text, dIndex + 4))
Else
Label24.Text = (Label24.Text)
End If
Dim myText2 = Label24.Text
Dim dIndex2 = myText2.IndexOf("Common")
If (dIndex2 > -1) Then
Label24.Text = (Label24.Text.Replace("Common", ""))
Else
Label24.Text = (Label24.Text)
End If
Label6.Text = (GetName(RequestWebData(strURL), 4))
Label6.Text = (GetName3(Label6.Text, 1))
Label6.Text = FormatNumber(Label6.Text, 2)
Label17.Text = (GetName(RequestWebData(strURL), 5))
Label21.Text = (GetName(RequestWebData(strURL), 7))
Dim x As String = GetName(RequestWebData(strURL), 8)
Label30.Text = GetName3(x, 1)
Label30.Text = FormatNumber(Label30.Text, 0)
Label32.Text = GetName3(x, 2)
TextBox2.Focus()
Function GetName(ByVal LineIn As String, ByVal i As Integer) As String
'Dim x As Integer
Return LineIn.Split(""",")(i)
End Function
Function GetName2(ByVal LineIn As String, ByVal i As Integer) As String
'Dim x As Integer
Return LineIn.Split("""")(i)
End Function
Function GetName3(ByVal LineIn As String, ByVal i As Integer) As String
'Dim x As Integer
Return LineIn.Split(",")(i)
End Function
Maybe it is so slow because of these three functions that I am using to split data?

how to use componentone c1printdocument in asp.net for reading text file and convert into pdf with format?

I am using the C1PrintDocument class to read a text file and convert into pdf in web. Actually it converts into pdf but without the format as like in text file.
For eg. I have a text file which has only one page. But it makes into two pages while convert into pdf. Below is the code what I use.
Imports System.IO
Imports C1.C1Preview
Imports C1.C1Pdf
Imports C1.Web.Wijmo.Controls.C1ReportViewer
Imports System.Runtime.Serialization.Formatters.Binary
Imports C1.C1Pdf.PdfDocumentInfo
Imports C1.C1Preview.C1PrintDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
Try
Dim strmappath As String = System.Web.HttpContext.Current.Server.MapPath("~")
Dim filename As String
filename = Path.Combine(Server.MapPath("~"), "12214.txt")
Dim sr As New System.IO.StreamReader(filename, System.Text.Encoding.UTF8)
Dim str As [String] = sr.ReadToEnd()
Dim doc1 As C1PrintDocument = C1ReportViewer.CreateC1PrintDocument()
Dim doc As New C1PrintDocument
doc.Pages(1).PageSettings.TopMargin = 0
doc.Pages(1).PageSettings.LeftMargin = 0
doc.Pages(1).PageSettings.RightMargin = 0
doc.StartDoc()
Dim overlay As New RenderArea()
overlay.Width = "100%"
overlay.Height = "100%"
overlay.Style.Borders.All = LineDef.Default
doc.PageLayout.Overlay = overlay
Dim lines As String() = System.IO.File.ReadAllLines(filename)
Dim linecnt As Integer = System.IO.File.ReadLines(filename).Count
Dim strpages1 As String()
ReDim strpages1(Math.Abs(linecnt / 66) - 1)
Dim intcnt As Integer
Dim intlinereadcnt As Integer
intlinereadcnt = 0
intcnt = 0
intlinereadcnt = 0
For Each line In lines
If intcnt <= 66 Then
If intcnt <> 66 Then
strpages1(intlinereadcnt) = strpages1(intlinereadcnt) &
line & vbCrLf
End If
intcnt = intcnt + 1
ElseIf intcnt = 67 Then
intlinereadcnt = intlinereadcnt + 1
intcnt = 0
End If
Next
Dim strPages As String() = str.Split(Chr(12))
Dim strPage As String = String.Empty
Dim txtPage As New C1.C1Preview.RenderText(doc)
With doc
.AllowNonReflowableDocs = True
For Each strPage In strpages1
If strPage.Length > 0 Then
txtPage.Text = strPage
txtPage.X = 150
doc.Style.TextColor = Drawing.Color.Blue
.RenderBlockText(txtPage.Text)
.Style.WordWrapMode = False
.NewPage()
End If
Next
End With
Dim m_pdfExporter As C1.C1Preview.Export.PdfExporter
m_pdfExporter = C1.C1Preview.Export.ExportProviders.
PdfExportProvider.NewExporter()
m_pdfExporter.Document = doc
m_pdfExporter.Export(Server.MapPath("~") & "12214" & ".pdf")
Dim sr2 As System.IO.MemoryStream
sr2 = New MemoryStream
doc.Save(sr2)
Dim biteArray As Byte() = New Byte(sr2.Length - 1) {}
sr2.Position = 0
sr2.Read(biteArray, 0, CInt(sr2.Length))
'm_pdfExporter.Export(Path.GetTempPath & "\" & "12214" & ".pdf")
Response.Clear()
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/pdf"
'Response.BinaryWrite(biteArray)
Response.AddHeader("Content-Disposition", "attachment;filename=" & "12214" & ".pdf")
Response.BinaryWrite(System.IO.File.ReadAllBytes(Server.MapPath("~") & "12214" & ".pdf"))
Catch ex As Exception
End Try
End Sub
Try using c1PrintDocument1.Export("filename.pdf", true) instead.
Thanks,
Richa

vb.net - Why do I get this error when trying to bubble sort a csv file?

I have a csv file which I'm trying to sort by data (numerical form)
The csv file:
date, name, phone number, instructor name
1308290930,jim,041231232,sushi
123123423,jeremy,12312312,albert
The error I get is: Conversion from string "jeremy" to type 'double'is not valid
Even though no where in my code I mention double...
My code:
Public Class Form2
Dim currentRow As String()
Dim count As Integer
Dim one As Integer
Dim two As Integer
Dim three As Integer
Dim four As Integer
'concatenation / and operator
'casting
Dim catchit(100) As String
Dim count2 As Integer
Dim arrayone(4) As Decimal
Dim arraytwo(4) As String
Dim arraythree(4) As Decimal
Dim arrayfour(4) As String
Dim array(4) As String
Dim bigstring As String
Dim builder As Integer
Dim twodata As Integer
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("D:\completerecord.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
Dim count As Integer
Dim currentField As String
count = 0
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
For Each currentField In currentRow
' makes one array to contain a record for each peice of text in the file
'MsgBox(currentField) '- test of Field Data
' builds a big string with new line-breaks for each line in the file
bigstring = bigstring & currentField + Environment.NewLine
'build two arrays for the two columns of data
If (count Mod 2 = 1) Then
arraytwo(two) = currentField
two = two + 1
'MsgBox(currentField)
ElseIf (count Mod 2 = 0) Then
arrayone(one) = currentField
one = one + 1
ElseIf (count Mod 2 = 2) Then
arraythree(three) = currentField
three = three + 1
ElseIf (count Mod 2 = 3) Then
arrayfour(four) = currentField
four = four + 1
End If
count = count + 1
'MsgBox(count)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Error Occured, Please contact Admin.")
End Try
End While
End Using
RichTextBox1.Text = bigstring
' MsgBox("test")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim NoMoreSwaps As Boolean
Dim counter As Integer
Dim Temp As Integer
Dim Temp2 As String
Dim listcount As Integer
Dim builder As Integer
Dim bigString2 As String = ""
listcount = UBound(arraytwo)
'MsgBox(listcount)
builder = 0
'bigString2 = ""
counter = 0
Try
'this should sort the arrays using a Bubble Sort
Do Until NoMoreSwaps = True
NoMoreSwaps = True
For counter = 0 To (listcount - 1)
If arraytwo(counter) > arraytwo(counter + 1) Then
NoMoreSwaps = False
If arraytwo(counter + 1) > 0 Then
Temp = arraytwo(counter)
Temp2 = arrayone(counter)
arraytwo(counter) = arraytwo(counter + 1)
arrayone(counter) = arrayone(counter + 1)
arraytwo(counter + 1) = Temp
arrayone(counter + 1) = Temp2
End If
End If
Next
If listcount > -1 Then
listcount = listcount - 1
End If
Loop
'now we need to output arrays to the richtextbox first we will build a new string
'and we can save it to a new sorted file
Dim FILE_NAME As String = "D:\sorted.txt"
'Location of file^ that the new data will be saved to
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
'If D:\sorted.txt exists then enable it to be written to
While builder < listcount
bigString2 = bigString2 & arraytwo(builder) & "," & arrayone(builder) + Environment.NewLine
objWriter.Write(arraytwo(builder) & "," & arrayone(builder) + Environment.NewLine)
builder = builder + 1
End While
RichTextBox2.Text = bigString2
objWriter.Close()
MsgBox("Text written to log file")
Else
MsgBox("File Does Not Exist")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
I think in this line is the problem
arrayone(one) = currentField
Here it trys to cast the string to a double. You have to use something like this:
arrayone(one) = Double.Parse(currentField)
or to have it a saver way:
Dim dbl As Double
If Double.TryParse(currentField, dbl) Then
arrayone(one) = dbl
Else
arrayone(one) = 0.0
End If