vjMarket vjMarket - 6 months ago 41
Vb.net Question

File already used by another process in vb.net using memorystream on my localhost

Below is Code. that convert image into string. I use memorystream and Convert.ToBase64String to get string of image. I also close memorystream object and free .but still also gives error.
The process cannot access the file 'File Name' because it is being used by another process.

Dim obj As New returnresult
Dim img As System.Drawing.Image
Dim memstream As System.IO.MemoryStream
Dim randomcls As New Random
Dim strImagePath as string="d:\a.jpg"
Try
Dim tmpFileName As String = ""

tmpFileName = randomcls.Next(1, 10) & System.IO.Path.GetExtension(strImagePath)

If System.IO.File.Exists(Server.MapPath("tmp\" & tmpFileName)) Then
System.IO.File.Delete(Server.MapPath("tmp\" & tmpFileName))
End If

System.IO.File.Copy(strImagePath, Server.MapPath("tmp\" & tmpFileName))
img = System.Drawing.Image.FromFile(Server.MapPath("tmp\" & tmpFileName))
memstream = New System.IO.MemoryStream()
img.Save(memstream, System.Drawing.Imaging.ImageFormat.Jpeg)
obj.strImage = Convert.ToBase64String(memstream.ToArray)
memstream.Close()
Return obj
Catch ex As Exception
Return obj
Finally
obj = Nothing
img = Nothing
memstream.Close()
memstream = Nothing
randomcls = Nothing
End Try


When ramdom class generate same number file and going to delete. it gives me error.

Answer

Try this. Remove This Code If possible....

tmpFileName = randomcls.Next(1, 10) & System.IO.Path.GetExtension(strImagePath)

If System.IO.File.Exists(Server.MapPath("tmp\" & tmpFileName)) Then
    System.IO.File.Delete(Server.MapPath("tmp\" & tmpFileName))
End If
System.IO.File.Copy(strImagePath, Server.MapPath("tmp\" & tmpFileName))
img = System.Drawing.Image.FromFile(Server.MapPath("tmp\" & tmpFileName))
memstream = New System.IO.MemoryStream()
img.Save(memstream, System.Drawing.Imaging.ImageFormat.Jpeg)
obj.strImage = Convert.ToBase64String(memstream.ToArray)
memstream.Close()
img = Nothing
memstream.Close()
memstream = Nothing

and write below .....

obj.strImage = Convert.ToBase64String(System.IO.File.ReadAllBytes(strImagePath))

. I hope this will help you.