Vb.net the process cannot access the file because it is being used by another process - vb.net

Hello i wanted to open an csv file and write text in it.
Here is the code:
Try
Dim path As String = "C:\Users\daaemoon\Desktop\Test.csv"
Dim reader As StreamReader = New System.IO.StreamReader(File.OpenRead(path))
Dim sw As New StreamWriter(path)
Dim s As String = String.Empty
While reader.Peek() >= 0
Dim line As String = reader.ReadLine()
Dim values As String() = line.Split(";"c)
listforfalsecsv.Add(values(0))
s = s + line + Chr(10)
End While
reader.Close()
sw.Write(s)
sw.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
i got the error by the following line:
Dim sw As New StreamWriter(path)
If i use the method reader.dispose() after that line Dim reader As StreamReader = New System.IO.StreamReader(File.OpenRead(path))
i come to the while loop, but than i got an error: From an closen Textreader could not been read.
I need help, please help me.

Related

Opening a CSV file as a OLEDB Connection converts file text to double

I'm opening up a couple of CSV files and reading them in as a DataTable per the example I found here. The issue I am running into it the basic query I'm using to import the data is converting the column of IP addresses into Doubles. So I want to read in 10.0.0.1 and it shows up as 10.001. How can I get this column to read in as a string? I would like to not double process the file if I can.
Query I'm using is basic and is as follows:
SELECT * FROM [ComputerList.csv]
Here is my function to open and read the CSV file into a DataTable
Public Function OpenFile(ByVal strFolderPath as String, ByVal strQuery as String) as DataTable
Dim strConn as String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFolderPath & ";Extended Propteries=""text; HDR=Yes;FMT=Delimited"""
Dim conn as OleDb.OleDbConnection = New OleDb.OleDbConnection(strConn)
Try
conn.Open()
Dim cmd as OleDb.OleDbCommand = New OleDb.OleDbCommand(strQuery, conn)
Dim da as OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter()
da.SelectCommand = cmd
Dim ds as DataSet = New DataSet()
da.Fill(ds)
da.Dispose()
return ds.Tables(0)
Catch
return Nothing
Finally
conn.Close()
End Try
End Function
i use this to read csv's and force all to string.
Public Function convert_csv_to_data_table(ByVal File As String, ByVal separator As String) As DataTable
Dim dt As New DataTable
Dim firstLine As Boolean = True
If IO.File.Exists(File) Then
Using sr As New StreamReader(File)
While Not sr.EndOfStream
If firstLine Then
firstLine = False
Dim cols = sr.ReadLine.Split(separator)
For Each col In cols
dt.Columns.Add(New DataColumn(col, GetType(String)))
Next
Else
Dim data() As String = sr.ReadLine.Split(separator)
dt.Rows.Add(data.ToArray)
End If
End While
End Using
End If
Return dt
End Function
EDIT:- this will only work with a separator btw
ok I tried variations of everyone's suggested and have settled on a hybrid between all of them. My goal was to read in a CSV file manipulate it in a DataTable form and them write it back out. Some of my CSV files had multiple lines with in a cell and some had deliminators within a cell. Below you can find my hybrid solution that utilized TextFieldParser to read in the file and break it up.
Public Function OpenFile(ByVal File as String, NyVal delim as String) as DataTable
Dim dt as New DataTable()
Dim firstline as Boolean = True
Using MyReader as New Microsoft.VisualBasic.FileIO.TextFieldParser(File)
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(delim)
Dim currentRow as String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
If firstline
firstline = false
For Each col in currentRow
dt.Columns.Add(New DataColumn(col.ToString(), System.Type.GetType("System.String")))
Next
Else
dt.Rows.Add(currentRow.ToArray())
End If
Catch ex as Microsoft.VisualBasic.FileIO.MalformedLineException
Console.WriteLIne("Line " + ex.Message + " is not valid and will be skipped")
End Try
End While
End Using
return dt
End Function

Trouble in saving a longblob image to database

I want to get the image from the datagridview then save it to the database. Can anyone help me with this? It will be so much appreciated
Below is my code in saving the image in the database. I don't know why but it doesn't actually save anything.
Try
connectionSync()
Dim a, b As String
Dim Sql = "INSERT INTO SAMPLE (ID, IMG)values(#a,#b)"
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
a = Me.DataGridView1.Rows(i).Cells(0).Value.ToString()
Dim cmd As New MySqlCommand(Sql, ConSync)
Dim memorystream1 As New MemoryStream()
Dim filename As String = DataGridView1.Rows(i).Cells(1).Value
Dim bitmaps As New Bitmap(filename)
bitmaps.Save(memorystream1, Imaging.ImageFormat.Jpeg)
Dim pic() As Byte = memorystream1.GetBuffer()
cmd.Parameters.AddWithValue("#a", a)
cmd.Parameters.AddWithValue("#b", bitmaps)
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
Next
ConSync.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try

VB.NET MD5 Comparing using large files

I'm trying to create a program in VB.NET 2010 that has a simple functionality.
It has to compare thousands of MD5 Hashes stored in a text file to current file MD5 Hash that program is automatically calculating while opening the file.
Like a antivirus scanner.
Actually my program use ReadAllText system to add all hashes from text file to a textbox and then it compare them.
Everyting is okay when Md5 database (that text file with hashes) is small but when the file get bigger, my program simply freezes after opening so I decided to use ReadLine instead of ReadAllText.
Now I can't use textbox any longer so give me a way how I can compare them.
I tried a way but it don't seem to work.
Here is my code using ReadLine.
Problem is on If Read contains(buff.tostring) it used to be
If textbox.text contains (buff.toString)
Here is the code
Try
TextBox2.Text = e.FullPath
ListBox3.Items.Add(TextBox2.Text.ToString)
Me.OpenFileDialog1.FileName = ""
Dim reader As StreamReader = New StreamReader("def.txt")
Dim read = reader.ReadLine()
Dim md5 As New MD5CryptoServiceProvider
Dim f As New FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read, &H2000)
f = New FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read, &H2000)
md5.ComputeHash(f)
Dim hash As Byte() = md5.Hash
Dim buff As New StringBuilder
Dim hashByte As Byte
For Each hashByte In hash
buff.Append(String.Format("{0:X2}", hashByte))
Next
f.Close()
If read.Contains(buff.ToString) Then
Me.OpenFileDialog1.FileName = e.FullPath
Form2.ShowDialog()
End If
Catch exception1 As Exception
ProjectData.SetProjectError(exception1)
Dim ex As Exception = exception1
ProjectData.ClearProjectError()
End Try
I would first create functions to split the functionality. It's a lot easier to understand the code afterward.
Store the hashes in a list, this list can then be cached is needed.
Try
TextBox2.Text = e.FullPath
ListBox3.Items.Add(TextBox2.Text.ToString)
Me.OpenFileDialog1.FileName = ""
Dim allHash As List(Of String) = GetAllHash()
Dim curHash As String = GetFileHash(e.FullPath)
If allHash.Contains(curHash) Then
Me.OpenFileDialog1.FileName = e.FullPath
Form2.ShowDialog()
End If
Catch exception1 As Exception
ProjectData.SetProjectError(exception1)
Dim ex As Exception = exception1
ProjectData.ClearProjectError()
End Try
Function GetAllHash() As List(Of String)
' Store the data in a list instead
Return System.IO.File.ReadAllLines("def.txt").ToList()
End Function
Function GetFileHash(ByVal filename As String) As String
Dim md5 As New MD5CryptoServiceProvider
' Only open the file once
Dim f As New FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, &H2000)
md5.ComputeHash(f)
Dim hash As Byte() = md5.Hash
Dim buff As New StringBuilder
For Each hashByte As Byte In hash
buff.Append(String.Format("{0:X2}", hashByte))
Next
f.Close()
Return buff.ToString()
End Function
I didn't compile this code, this is just a example to show you what can be done.

The process cannot access the file 'file.csv' because it is being used by another process

I have a code which process each file in a folder and send the data in the file to SQL Database and then deletes the file. But often i get this Exception "The process cannot access the file 'file.csv' because it is being used by another process." Please can anyone point me out in the right direction, will really appreciate that.
The code is shown below :
Dim dirinfo As DirectoryInfo
Dim allFiles() As FileInfo
dirinfo = New DirectoryInfo("E:\SQLUPDATE\CAC")
allFiles = dirinfo.GetFiles("*.csv")
If allFiles.Length <> 0 Then
Try
For Each fl As FileInfo In allFiles
'MsgBox(fl.FullName.ToString())
Dim con As SqlConnection = New SqlConnection(SQL_con2)
Dim sr As StreamReader = New StreamReader(fl.FullName)
Dim line As String = sr.ReadLine
Dim value() As String = line.Split(Microsoft.VisualBasic.ChrW(44))
Dim dt As DataTable = New DataTable
Dim row As DataRow
For Each dc As String In value
dt.Columns.Add(New DataColumn(dc))
Next
While Not sr.EndOfStream
value = sr.ReadLine.Split(Microsoft.VisualBasic.ChrW(44))
If (value.Length = dt.Columns.Count) Then
row = dt.NewRow
row.ItemArray = value
dt.Rows.Add(row)
End If
End While
Dim bc As SqlBulkCopy = New SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock)
bc.DestinationTableName = "[DB].[dbo].[CAC_LData]"
bc.BatchSize = dt.Rows.Count
con.Open()
bc.WriteToServer(dt)
bc.Close()
con.Close()
sr.Close()
System.IO.File.Delete(fl.FullName)
sr.Dispose()
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If

Save file if error reading with Stream Reader

I am trying to parse a uploaded txt file. I need to save the file if there is an error parsing it. The problem is that the parser is using a Stream Reader and if an error occurs it just saves the empty file and not the file contents.
Dim file As HttpPostedFile = context.Request.Files(0)
If Not IsNothing(file) AndAlso file.ContentLength > 0 AndAlso Path.GetExtension(file.FileName) = ".txt" Then
Dim id As Integer = (Int32.Parse(context.Request("id")))
Try
ParseFile(file, id)
context.Response.Write("success")
Catch ex As Exception
Dim filename As String = file.FileName
Dim uploadPath = context.Server.MapPath("~/Errors/MyStudentDataFiles/")
file.SaveAs(uploadPath + id.ToString() + filename)
End Try
Else
context.Response.Write("error")
End If
My ParseFile method is something like this
Protected Sub ParseFile(ByVal studentLoanfile As HttpPostedFile, ByVal id As Integer)
Using r As New StreamReader(studentLoanfile.InputStream)
line = GetLine(r)
End Using
End Sub
Is there a way to Clone the file before it gets passed into the parseFile sub or a way to read the file without loosing the contents?
Thanks in advance
For anyone who runs into this problem in the future, I ended up reading the file to the end and saving it into a variable. Then converted it back into a memory stream to use for the parser. If an error occurs, I just create a new file with the string. This is the code I used.
Dim id As Integer = (Int32.Parse(context.Request("id")))
'Read full file for error logging
Dim content As String = [String].Empty
Using sr = New StreamReader(uploadedFile.InputStream)
content = sr.ReadToEnd()
End Using
'Convert it back into a stream
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(content)
Dim stream As New MemoryStream(byteArray)
Try
ParseFile(stream, id, content)
context.Response.Write("success")
Catch ex As Exception
Dim filename As String = uploadedFile.FileName
Dim uploadPath = context.Server.MapPath("~/Errors/MyStudentDataFiles/")
'Save full file on error
Using sw As StreamWriter = File.CreateText(uploadPath + id.ToString() + filename)
sw.WriteLine(content)
End Using
context.Response.Write("error")
Throw ex
End Try
Else
context.Response.Write("error")
End If