creating csv file in VB2010 - vb.net

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

Related

How to end a for loop without a comma? VB.NET

i was about to save each number from one cell using for loop here is my code:
For Each node As XmlNode In xmlnode
Dim X As String
Dim Y As String
Dim Z As String
X = node.SelectSingleNode("X").InnerText
Y = node.SelectSingleNode("Y").InnerText
Z = node.SelectSingleNode("Z").InnerText
Dim noOfPts As Integer = 0 'number of data points in data
For i As Double = 0 To noOfPts
result = X + ","
result2 = Y + ","
Next
Next
the thing is i'm going to end the loop without saving the comma. Instead of this "1,2,3,4,5," it should be like this "1,2,3,4,5" remove the comma from the end of the loop.
With StringBuilder you can simplify the loop by removing if statements and make more efficient in most of the cases (especially when you building a string in the loop).
Dim xBuilder AS New StringBuilder()
Dim yBuilder As New StringBuilder()
Dim delimiter As String = ", "
For Each node As XmlNode In xmlnode
Dim X As String = node.SelectSingleNode("X").InnerText
Dim Y As String = node.SelectSingleNode("Y").InnerText
Dim Z As String = node.SelectSingleNode("Z").InnerText
For i As Integer = 0 To noOfPts
xBuilder.Append(X).Append(delimiter)
yBuilder.Append(Y).Append(delimiter)
Next
Next
' use Math.Max to prevent exception if builder is empty
xBuilder.Length = Math.Max(xBuilder.Length - delimiter.Length, 0)
yBuilder.Length = Math.Max(yBuilder.Length - delimiter.Length, 0)
Dim resultX As String = xBuilder.ToString() ' 1, 2, 3, 4, 5
Dim resultY As String = yBuilder.ToString()
We are removing last "redundant" delimiter by "cutting" stringbuilder's length by length of delimiter.
For using String.Join you need to create a collection of values first
Dim xValues AS New List<string>()
Dim yValues As New List<string>()
For Each node As XmlNode In xmlnode
Dim X As String = node.SelectSingleNode("X").InnerText
Dim Y As String = node.SelectSingleNode("Y").InnerText
Dim Z As String = node.SelectSingleNode("Z").InnerText
For i As Integer = 0 To noOfPts
xValues.Add(X)
xValues.Add(Y)
Next
Next
Dim resultX As String = String.Join(", ", xValues) ' 1, 2, 3, 4, 5
Dim resultY As String = String.Join(", ", yValues)
I like to do it this way:
For i As Double = 0 To noOfPts
If result <> "" Then result &= ", "
result &= X
If result2 <> "" Then result2 &= ", "
result2 &= Y
Next
Have fun!

The copy process is very slow with this function vb.net

I use this function for copying some files from the Source folder to the Destination folder, but the copying is needed more time than usual.
Sub SyncFiles(Lbl_Percentage As Label, Lbl_FileName As Label, PrgrsBar As ProgressBar)
Try
Dim Sql As String = "SELECT GroupID FROM Tbl_Current"
Dim GetGroupID = MsAcc_RetriveTemp(Sql, 0)
Dim Sql1 As String = "Select * FROM Tbl_SyncPath where ID=" & GetGroupID
Dim Src As String = MsAcc_RetriveTemp(Sql1, 1)
Dim Des As String = MsAcc_RetriveTemp(Sql1, 2)
If Not IO.Directory.Exists(Des) Then IO.Directory.CreateDirectory(Des)
Dim fls() As String = IO.Directory.GetFiles(Des)
PrgrsBar.Value = 0
PrgrsBar.Maximum = fls.Count
For Each fn As String In fls
Dim filename As String = IO.Path.GetFileName(fn)
My.Computer.FileSystem.CopyDirectory(Des, Src, True)
PrgrsBar.Value += 1 'add 1 to the ProgressBar`s value
Dim Percntge As Integer = (PrgrsBar.Value / fls.Count) * 100
Lbl_Percentage.Text = Percntge & " %"
Lbl_FileName.Text = "جاري تحديث ملف: " & filename
Application.DoEvents()
Lbl_FileName.Text = "اكتمل عملية التحديث."
Next
Catch ex As Exception
End Try
End Sub
You copy all the files in the folder for each files.
For Each fn As String In fls
Dim filename As String = IO.Path.GetFileName(fn)
My.Computer.FileSystem.CopyDirectory(Des, Src, True) ' <--- No file specified
PrgrsBar.Value += 1 'add 1 to the ProgressBar`s value
Dim Percntge As Integer = (PrgrsBar.Value / fls.Count) * 100
Lbl_Percentage.Text = Percntge & " %"
Lbl_FileName.Text = "جاري تحديث ملف: " & filename
Application.DoEvents()
Lbl_FileName.Text = "اكتمل عملية التحديث."
Next
Put this outside the loop
My.Computer.FileSystem.CopyDirectory(Des, Src, True)
For Each fn As String In fls
' ...
Next
Also, seems like des and src are mixed up.

Variable '' is used before it has been assigned a value.

I'm trying to make a program that downloads a bunch of domains and adds them windows hosts file but I'm having a bit of trouble. I keep getting an error when I try storing them in a list. I don't get why it doesn't work.
Sub Main()
Console.Title = "NoTrack blocklist to Windows Hosts File Converter"
Console.WriteLine("Downloading . . . ")
Dim FileDelete As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt"
If System.IO.File.Exists(FileDelete) = True Then
System.IO.File.Delete(FileDelete)
End If
download()
Threading.Thread.Sleep(1000)
Dim s As New IO.StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt", True)
Dim tempRead As String ' = s.ReadLine
Dim tempSplit As String() ' = tempRead.Split(New Char() {" "})
Dim i As Integer = 0
Dim tempStore As String()
s.ReadLine()
s.ReadLine()
Do Until s.EndOfStream = True
tempRead = s.ReadLine
tempSplit = tempRead.Split(New Char() {" "})
Console.WriteLine(tempSplit(0))
tempStore(i) = tempSplit(0)'The part that gives me the error
i = i + 1
Loop
Console.ReadKey()
End Sub
Sub download()
Dim localDir As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
'"Enter file URL"
Dim url As String = "https://quidsup.net/notrack/blocklist.php?download"
'"Enter directory"
Dim dirr As String = localDir & "/Downloads" & "/notracktemp.txt"
My.Computer.Network.DownloadFile(url, dirr)
'System.IO.File.Delete(localDir & "/notracktemp.txt")
End Sub
tempStore() has to have a size
count number of lines in file with loop, then declare it as tempStore(i) where i is the amount of lines. Here is a function that counts the lines.
Function countlines()
Dim count As Integer
Dim s As New IO.StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt", True)
s.ReadLine()
s.ReadLine()
count = 0
Do Until s.EndOfStream = True
s.ReadLine()
count = count + 1
Loop
Console.WriteLine(count)
Return count
Console.ReadKey()
End Function
Then what you do is:
Dim count As Integer
count = countlines()
Dim tempStore(count) As String

vb.net how do i add long text into csv

hello this is my firs thread ,
i'm trying to convert description of this page (https://www.tokopedia.com/indoislamicstore/cream-zaitun-arofah)
with regex and replace <br/> tag with new line and convert it to csv .
the datagridview it's alright but the csv got screwed
this is my code :
Dim dskrip As New System.Text.RegularExpressions.Regex("<p itemprop=""description"" class=""mt-20"">(.*?)\<\/p>\<\/div>")
Dim dskripm As MatchCollection = dskrip.Matches(rssourcecode0)
For Each itemdskrm As Match In dskripm
getdeskripsinew = itemdskrm.Groups(1).Value
Next
Dim deskripsinew As String = Replace(getdeskripsinew, ",", ";")
Dim deskripsitotal As String = Replace(deskripsinew, "<br/>", Environment.NewLine)
' ListView1.s = Environment.NewLine & deskripsinew
txtDeskripsi.Text = deskripsitotal
datascrapes.ColumnCount = 5
datascrapes.Columns(0).Name = "Title"
datascrapes.Columns(1).Name = "Price"
datascrapes.Columns(2).Name = "Deskripsi"
datascrapes.Columns(3).Name = "Gambar"
datascrapes.Columns(4).Name = "Total Produk"
Dim row As String() = New String() {getname, totalprice, deskripsitotal, directoryme + getfilename, "10"}
datascrapes.Rows.Add(row)
Dim filePath As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\" & "Tokopedia_Upload.csv"
Dim delimeter As String = ","
Dim sb As New StringBuilder
For i As Integer = 0 To datascrapes.Rows.Count - 1
Dim array As String() = New String(datascrapes.Columns.Count - 1) {}
If i.Equals(0) Then
For j As Integer = 0 To datascrapes.Columns.Count - 1
array(j) = datascrapes.Columns(j).HeaderText
Next
sb.AppendLine(String.Join(delimeter, array))
End If
For j As Integer = 0 To datascrapes.Columns.Count - 1
If Not datascrapes.Rows(i).IsNewRow Then
array(j) = datascrapes(j, i).Value.ToString
End If
Next
If Not datascrapes.Rows(i).IsNewRow Then
sb.AppendLine(String.Join(delimeter, array))
End If
Next
File.WriteAllText(filePath, sb.ToString)
this is the csv file
I'm not sure where your problem is looking at the CSV file, but there are certain cases where you'll want to quote the values for a CSV. There's no official spec but RFC 4180 is often used as an unofficial standard. I would recommend using a library like CSV Helper

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