Updating values in .csv file depend to values in second .csv - vb.net

I have two csv files, which contains some data. One of them looks like this:
drid;aid;1date;2date;res;
2121;12;"01.11.2019 06:49";"01.11.2019 19:05";50;
9;10;"01.11.2019 10:47";"01.11.2019 11:33";0;
72;33;"01.11.2019 09:29";"01.11.2019 14:19";0;
777;31;"03.11.2019 04:34";"03.11.2019 20:38";167,35;
Second scv looks like this
datetime;res;drid
"2019-11-01 09:02:00";14,59;2121
"2019-11-03 12:59:00";25,00;777
My target to compare day of date also "drid" and if they are the same in both files then get sum of "res" and replace values of "res" in first csv. Result have to looks like this:
2121;12;"01.11.2019 06:49";"01.11.2019 19:05";64,59;
9;10;"01.11.2019 10:47";"01.11.2019 11:33";0;
72;33;"01.11.2019 09:29";"01.11.2019 14:19";0;
777;31;"03.11.2019 04:34";"03.11.2019 20:38";192,35;
What I have to do to obtain that results in vb.net? I tried to use LINQ Query, but with no results, because I'm newbie and I didn't find way to declare variables in two files and then compare it.
Ok, with .bat I made join both csv in one big.csv and tried to obtain results from same file, but again without success. Last one code is:
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
Dim Raplines As String() = IO.File.ReadAllLines("C:\Users\big.csv")
Dim strList As New List(Of String)
Dim readFirst As Boolean
For Each line In Raplines
If readFirst Then
Dim strValues As String() = line.Split(";")
Dim kn1 As String = strValues(0)
Dim kn2 As String = strValues(59)
Dim pvm1 As Date = strValues(2)
Dim pvm1Changed = pvm1.ToString("dd")
Dim pvm2 As Date = strValues(3)
Dim pvm2Changed = pvm2.ToString("dd")
Dim pvm3 As Date = strValues(60)
Dim pvm3Changed = pvm3.ToString("dd")
Dim Las1 As Decimal = strValues(9)
Dim Las2 As Decimal = strValues(61)
Dim sum As Decimal = Las1 - Las2
If kn1 = kn2 And pvm3Changed = pvm1Changed Or pvm3Changed = pvm2Changed Then
strValues(9) = sum
strList.Add(String.Join(";", strValues))
End If
End If
readFirst = True
Next
IO.File.WriteAllLines("C:\Users\big_new.csv", strList.ToArray())
End Sub

Instead of changing the existing file I wrote a new one. I used a StringBuilder so the runtime would not have to create and throw away so many strings. StringBuilder are mutable unlike Strings. I parsed the different formats of the dates and used .Date to disregard the Times.
Private Sub ChangeCVSFile()
Dim lines1 = File.ReadAllLines("C:\Users\someone\Desktop\CSV1.cvs")
Dim lines2 = File.ReadAllLines("C:\Users\someone\Desktop\CSV2.cvs")
Dim sb As New StringBuilder
For Each line1 In lines1
Dim Fields1 = line1.Split(";"c) 'drid;aid;1date;2date;res
For Each line2 In lines2
Dim Fields2 = line2.Split(";"c) 'datetime;res;drid
'
' Trim the exta double quotes "01.11.2019 06:49"
Dim d1 = DateTime.ParseExact(Fields1(2).Trim(Chr(34)), "dd.MM.yyyy hh:mm", CultureInfo.InvariantCulture).Date
' "2019-11-01 09:02:00"
Dim d2 = DateTime.ParseExact(Fields2(0).Trim(Chr(34)), "yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture).Date
If Fields1(0) = Fields2(2) AndAlso d1 = d2 Then
Dim sum = CDec(Fields1(4)) + CDec(Fields2(1))
Fields1(4) = sum.ToString
End If
Next
sb.AppendLine(String.Join(";", Fields1))
Next
File.WriteAllText("C:\Users\someone\Desktop\CSV3.cvs", sb.ToString)
End Sub

Related

Currently having problems with deleting/overwriting from a file

I'm currently having problems trying to delete a line from a file and replace that line with different text (overwrite the line)
The code initially starts by extracting file contents to find the
DepartmentDetails which can be used to find DepartmentBudget and subtract AmountDue and then create a new DepartmentDetails with the new budget
Once this is complete the code will add the N̳e̳w̳ DepartmentDetails which will leave the code with having the O͟l͟d͟ and the N̳e̳w̳ DepartmentDetails in the same folder.
The code should then delete the O͟l͟d͟ DepartmentDetails from the file making the N̳e̳w̳ DepartmentBudget take it's place. i.e. Overwrite the O͟l͟d͟ DepartmentDetails with the new one.
The problem is that the code does not delete the O͟l͟d͟ DepartmentBudget but adds a line space in between the O͟l͟d͟ and N̳e̳w̳ instead.
Private Sub BtnBillDept_Click(sender As Object, e As EventArgs) Handles BtnBillDept.Click
Dim DepartmentStore As New Department
Dim Order() As String = File.ReadAllLines(Dir$("OrderDetails.Txt"))
Dim OrderID As String = TxtOrderID.Text
Dim AmountDue As String = TxtAmountDue.Text
Dim DeptID As String = (Trim(Mid(Order(OrderID), 5, 4)))
Dim DepartmentDetails() As String = File.ReadAllLines(Dir$("DepartmentDetails.Txt"))
Dim DepartmentBudget As String = (Trim(Mid(DepartmentDetails(DeptID), 35, 6)))
Dim FormattedBudget As String = FormatCurrency(DepartmentBudget, 2)
Dim YesNo As String
Dim sw As New StreamWriter("DepartmentDetails.txt", True)
DepartmentBudget = FormattedBudget - AmountDue
DepartmentStore.DepartmentID = LSet(DeptID, 4)
DepartmentStore.DepartmentHead = LSet((Trim(Mid(DepartmentDetails(DeptID), 5, 20))), 20)
DepartmentStore.DepartmentName = LSet((Trim(Mid(DepartmentDetails(DeptID), 25, 10))), 10)
DepartmentStore.DepartmentBudget = LSet(DepartmentBudget, 9)
DeptID = UBound(DepartmentDetails)
DepartmentDetails(DeptID) = ""
File.WriteAllLines("DepartmentDetails", DepartmentDetails)
sw.WriteLine(DepartmentStore.DepartmentID & DepartmentStore.DepartmentHead & DepartmentStore.DepartmentName & DepartmentStore.DepartmentBudget)
sw.Close()`
'***********************Having Problems Here***********************
DepartmentDetails = File.ReadAllLines(Dir$("DepartmentDetails.Txt"))
DepartmentDetails(DeptID) = ""
File.WriteAllLines("DepartmentDetails", DepartmentDetails)
'************************Having Problems Here**************************
YesNo = MsgBox("Department has been billed. Would you like to delete the bill?", vbYesNo)
If YesNo = vbYes Then
End If
End Sub
Who decided that this text file would be formatted with fixed length fields? All this trimming and padding could be avoided with a simple comma delimited file or an xml file or a database where it really belongs.
Code is not tested. Comments and explanations in-line.
'I assume you have a class that looks something like this
'This uses automatic properties to save you having to
'type a getter, setter and backer field (the compiler adds these)
Public Class Department
Public Property DepartmentID As Integer
Public Property DepartmentHead As String
Public Property DepartmentName As String
Public Property DepartmentBudget As Decimal
End Class
Private Sub BtnBillDept_Click(sender As Object, e As EventArgs) Handles BtnBillDept.Click
Dim DepartmentStore As New Department
'Drag an OpenFileDialog from the ToolBox to your form
'It will appear in the lower portion of the design window
Dim MyFilePath As String = ""
OpenFileDialog1.Title = "Select OrderDetails.Txt"
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
MyFilePath = OpenFileDialog1.FileName
End If
Dim Order() As String = File.ReadAllLines(MyFilePath)
'Changed data type, you use OrderID as an index for the Order array so it must be an Integer
Dim OrderID As Integer
'TryParse will check if you have a valid interger and fill OrderID variable
If Not Integer.TryParse(TxtOrderID.Text, OrderID) Then
MessageBox.Show("Please enter a valid Order ID.")
Return
End If
'EDIT per comment by Codexer
If OrderID > Order.Length - 1 Then
MessageBox.Show("Order Number is too high")
Return
End If
Dim AmountDue As Decimal
If Decimal.TryParse(TxtAmountDue.Text, AmountDue) Then
MessageBox.Show("Please enter a valid Amount Due")
Return
End If
'I hope you realize that the first index in Order is zero
'Mid is an old VB6 method around for compatibility
'Use the .net Substring (startIndex As Integer, length As Integer)
'The indexes in the string start with zero
Dim DeptID As Integer = CInt(Order(OrderID).Substring(5, 4).Trim) '(Trim(Mid(Order(OrderID), 5, 4)))
OpenFileDialog1.Title = "Select DepartmentDetails.txt"
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
MyFilePath = OpenFileDialog1.FileName
End If
Dim DepartmentDetails() As String = File.ReadAllLines(MyFilePath)
Dim DepartmentBudget As Decimal = CDec(DepartmentDetails(DeptID).Substring(35, 6).Trim) '(Trim(Mid(DepartmentDetails(DeptID), 35, 6)))
'You don't need to format anything until you want to display it
'Dim FormattedBudget As String = FormatCurrency(DepartmentBudget, 2)
'A MessageBox returns a DialogResult
Dim YesNo As DialogResult
Dim sw As New StreamWriter(MyFilePath, True)
'Shorcut way to write DepartmentBudget - AmountDue
DepartmentBudget -= AmountDue
'Set the property in the class with the proper data type
DepartmentStore.DepartmentID = DeptID
'Then prepare a string for the writing to the fil
Dim PaddedID = CStr(DeptID).PadLeft(4)
'The .net replacement for LSet is .PadLeft
DepartmentStore.DepartmentHead = DepartmentDetails(DeptID).Substring(5, 20).Trim.PadLeft(20)
DepartmentStore.DepartmentName = DepartmentDetails(DeptID).Substring(25, 10).Trim.PadLeft(20)
'Set the property in the class with the proper data type
DepartmentStore.DepartmentBudget = DepartmentBudget
'Then prepare a string for the writing to the fil
Dim PaddedBudget = CStr(DepartmentBudget).PadLeft(9)
sw.WriteLine(PaddedID & DepartmentStore.DepartmentHead & DepartmentStore.DepartmentName & PaddedBudget)
sw.Close()
'***********************Having Problems Here***********************
'This is using the path from the most recent dialog
DepartmentDetails = File.ReadAllLines(MyFilePath)
'Here you are changing the value of one of the elements in the DepartmentDetails array
DepartmentDetails(DeptID) = ""
'Public Shared Sub WriteAllLines (path As String, contents As String())
'The string "DepartmentDetails" is not a path
File.WriteAllLines(MyFilePath, DepartmentDetails)
'************************Having Problems Here**************************
YesNo = MessageBox.Show("Department has been billed. Would you like to delete the bill?", "Delete Bill?", MessageBoxButtons.YesNo)
If YesNo = DialogResult.Yes Then
End If
End Sub

Null Exception while loading my file to listbox.

I have a problem. I'm trying to load data to listbox , but when I click start I get an unhandled exception that states values cannot be null. I've bolded where the issue is.
I'm trying to create a library database, and would really appreciate if someone could help me fix this issue. Thanks!
Public Class frmLibrary
Structure BookData
Dim Title As String
Dim Author As String
Dim ISBN As Integer
Dim YearPublished As Integer
End Structure
Dim bookinfo() As BookData 'Array
Private Sub frmLibrary_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim bookfiles() As String = IO.File.ReadAllLines("LibraryDatabase.txt")
Dim n As Integer = bookfiles.Count - 1
ReDim bookinfo(n)
Dim line As String
Dim books() As String 'books are the parts
'use the split methods to assign values to the members of the structure variable.
For i As Integer = 0 To n ---**>Why is this value null???????**
line = bookfiles(i)
books = line.Split(","c) '
bookinfo(i).Title = books(0)
bookinfo(i).Author = books(1)
bookinfo(i).ISBN = books(2)
bookinfo(i).YearPublished = books(3)
Next
Dim query = From book In bookinfo
Select book.Title, book.Author, book.ISBN, book.YearPublished
DGVBookInfo.DataSource = query.ToList
DGVBookInfo.Columns("Title").HeaderText = "Title"
DGVBookInfo.Columns("Author").HeaderText = "Author"
DGVBookInfo.Columns("ISBN").HeaderText = "ISBN"
DGVBookInfo.Columns("Year Published").HeaderText = "Year Published"
DGVBookInfo.AutoResizeColumns()
DGVBookInfo.RowHeadersVisible = False
End Sub

Item pairing between two .txt

I have been trying to combine or pair two text files.
One file contains User:Key
The other file contains Key:Pass
I want a 3rd text file created containing the corresponding pairs of User:Pass based on the key matching.
Here is what Ive tried most recently
Private Sub Rotate()
Dim Cracked() As String = IO.File.ReadAllLines(TextBox1.Text)
For Each lineA In Cracked
TextBox5.Text = lineA
check()
Next
End Sub
Private Sub check()
Dim toCheck() As String = TextBox5.Text.Split(":")
Dim tHash As String = toCheck(0)
Dim tPass As String = toCheck(1)
Dim lines1() As String = IO.File.ReadAllLines(TextBox2.Text)
For Each line In lines1
If lines1.Contains(tHash) Then
Dim toAdd() As String = line.Split(":")
Dim uHash As String = toCheck(0)
Dim uUser As String = toCheck(1)
ListBox1.Items.Add(uUser + ":" + tPass)
End If
Next
End Sub
Public Sub CopyListBoxToClipboard(ByVal ListBox2 As ListBox)
Dim buffer As New StringBuilder
For i As Integer = 0 To ListBox1.Items.Count - 1
buffer.Append(ListBox1.Items(i).ToString)
buffer.Append(vbCrLf)
Next
My.Computer.Clipboard.SetText(buffer.ToString)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
CopyListBoxToClipboard(ListBox1)
End Sub
The delimiter changes but for now the : works.
I tried splitting and matching but either the textbox5 does not rotate or it rotates through the list and thats all.
Something like this?
Dim KeyPassFile As String = "..."
Dim UserKeyFile As String = "..."
Dim UserPassFile As String = "..."
Dim KeyPass As New Hashtable
' Read Key:Pass file
For Each Line In IO.File.ReadAllLines(KeyPassFile)
Dim iStart = Line.IndexOf(":")
Dim Key = Line.Substring(0, iStart)
Dim Pass = Line.Substring(iStart + 1)
KeyPass.Add(Key, Pass)
Next
' Create User:Pass file
Dim OutFile = IO.File.CreateText(UserPassFile)
' Read User:Key file
For Each Line In IO.File.ReadAllLines(UserKeyFile)
Dim iStart = Line.IndexOf(":")
Dim User = Line.Substring(0, iStart)
Dim Key = Line.Substring(iStart + 1)
If KeyPass.ContainsKey(Key) Then
' We have a match for the key, write it to the file
OutFile.WriteLine(User & ":" & KeyPass(Key))
End If
Next
OutFile.Close()
This will probably not work for very large files that doesn't fit in memory, and there is no duplicate check for the key insertion in the hashtable, but I'll leave something for you to do.. :)
Also, in your code, you read the file specified in the TextBox2.Text as many times as there are lines in the TextBox1.Text file..

How to Replace string and loop between commas with another string

can you help me how to get Index of the same string and replace it one by one with another string?
Here my example code :
For i As Integer = 0 To 10
Dim str As String = "abcd,abcd,abcd,abcd,abcd,abcd,abcd,abcd"
Dim replace As String = "efgh"
Dim value As String
value = str.Replace("abcd", replace)
TextBox4.AppendText(value)
Next
The value will be result : efgh,efgh,efgh,efgh,efgh...
How i can create the result like this :
efgh,abcd,abcd,abcd,abcd,abcd...
for the next loop it will be like this :
abcd,efgh,abcd,abcd,abcd,abcd...
for the next loop it will be like this :
abcd,abcd,efgh,abcd,abcd,abcd...
Thank you
There are lots of ways this could be done. One perhaps inefficient way would be to split the string at the commas, replace the appropriate item in the resulting array, and then join the array back up.
Dim str As String = "abcd,abcd,abcd,abcd,abcd,abcd,abcd,abcd"
Dim replace As String = "efgh"
For i As Integer = 0 To str.Count(Function(x) x = ","c)
Dim strParts = str.Split(","c)
strParts(i) = replace
Dim value As String = String.Join(",", strParts)
Console.WriteLine(value)
Next
Output:
efgh,abcd,abcd,abcd,abcd,abcd,abcd,abcd
abcd,efgh,abcd,abcd,abcd,abcd,abcd,abcd
abcd,abcd,efgh,abcd,abcd,abcd,abcd,abcd
abcd,abcd,abcd,efgh,abcd,abcd,abcd,abcd
abcd,abcd,abcd,abcd,efgh,abcd,abcd,abcd
abcd,abcd,abcd,abcd,abcd,efgh,abcd,abcd
abcd,abcd,abcd,abcd,abcd,abcd,efgh,abcd
abcd,abcd,abcd,abcd,abcd,abcd,abcd,efgh
As #Mark mentioned there are lots of ways this could be done. One of this ways to add and remove ranges in a string is to use the StringBuilder.
Imports System.Text
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i As Integer = 0 To 35 Step 5
Dim sDefaultString As String = "abcd,abcd,abcd,abcd,abcd,abcd,abcd,abcd"
Dim sbText = New StringBuilder(sDefaultString)
sbText.Remove(i, 4)
sbText.Insert(i, "efgh")
TextBox1.AppendText(sbText.ToString & vbNewLine)
Next
End Sub
End Class

Copying data from text file to array

I'm trying to copy data from text file to array, I got error Index was outside the bounds of the array.
Dim vstring(-1) As String
Dim vid(-1) As String
Dim index As Integer
Dim vText As String = ""
Dim vFileName As String = "C:\Users\suman\Documents\Visual Studio 2010\Projects\Ass3_2076004\student.txt"
Dim vAvgValue As Integer
Dim vErrorMsg As String = ""
If (Txt_IdNumber.Text).Length = 5 Then
Dim rvSR As New IO.StreamReader(vFileName)
Do While rvSR.Peek <> -1
vText = rvSR.ReadLine()
vstring = vText.Split(",")
vid(index) = vstring(0)'error
index = index + 1
Loop
Dim vstring() as String
Dim vFileName As String = "C:\Users\suman\Documents\Visual Studio 2010\Projects\Ass3_2076004\student.txt"
If Txt_IdNumber.Text.Length = 5 Then
Using rvSR As New IO.StreamReader(vFileName)
vstring = rvSR.ReadLines().Select(Function(s) s.Split(","c)(0)).ToArray()
End Using
End If
First, you should probably declare vstring as an unsized array. Like this:
Dim vString() as string
Second, Since you don't know how many lines you need, declare vid as list. Like this:
Dim vid as List(of string)
Then, before you split the string, you should make sure it actually contains a comma. Like this:
Do While rvSR.Peek <> -1
vText = rvSR.ReadLine()
If vText.Contains(",") Then
vstring = vText.Split(",")
vid.add(vstring(0))
End If
Loop
'at the end, you can convert vid from a list to an array, if you want
Dim arr() as string = vid.ToArray()