Cannot read file from disk - vb.net

When I upload an excel file from my vb app, it's fine for the first time. If I try it a second time I am having this error: The process cannot access the file (path) because it is bein used by another process. Below is my code:
Dim fd As OpenFileDialog = New OpenFileDialog()
fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.xlsx)|*.xlsx|All files (*.xlsx)|*.xlsx"
fd.FilterIndex = 2
fd.RestoreDirectory = True
Dim myStream As Stream = Nothing
If fd.ShowDialog() = DialogResult.OK Then
Try
myStream = fd.OpenFile()
If (myStream IsNot Nothing) Then
workbook = APP.Workbooks.Open(fd.FileName)
worksheet = workbook.Worksheets("sheet1")
TextBox1.Text = worksheet.Cells(1, 7).Value
TextBox2.Text = worksheet.Cells(2, 7).Value
TextBox3.Text = worksheet.Cells(3, 7).Value
l1.Text = worksheet.Cells(2, 1).Value * 10
w1.Text = worksheet.Cells(2, 2).Value * 10
q1.Text = worksheet.Cells(2, 3).Value
p1.Text = worksheet.Cells(2, 4).Value..........
Dim Values(119, 3) As String
Values(0, 0) = l1.Text
Values(0, 1) = w1.Text
Values(0, 2) = q1.Text
Values(0, 3) = p1.Text.........
Dim add As Integer = 0
Dim pressing As Integer = 0
If adding.Text = "50" Or adding.Text = "" Then
add = 50
Else
add = Convert.ToInt16(adding.Text)
End If
If press.Text = "20" Or press.Text = "" Then
pressing = 20
Else
pressing = Convert.ToInt16(press.Text)
End If
Dim l As Integer
Dim w As Integer
Dim machinearea As Integer
Dim connetionString As String
Dim cnn As SqlConnection
connetionString = "Data Source=.;Initial Catalog=lumber;User ID=sa;Password=sasql"
cnn = New SqlConnection(connetionString)
Dim cmd As SqlCommand
Dim myreader As SqlDataReader
Dim query As String
query = "SELECT length,width from marea"
cmd = New SqlCommand(query, cnn)
cnn.Open()
myreader = cmd.ExecuteReader()
If myreader.Read() Then
l = myreader.Item("length")
w = myreader.Item("width")
End If
cnn.Close()
machinearea = l * w
Dim allTextBoxes2 = From txt In Me.Panel1.Controls.OfType(Of TextBox)()
Order By txt.TabIndex
Dim txtList2 = allTextBoxes2.ToList()
For i As Int32 = 0 To txtList2.Count - 1
Dim thisTxt = txtList2(i)
Dim nextIndex = If(i + 1 >= txtList2.Count, 0, i + 1)
Dim prevIndex = If(i - 1 < 0, txtList2.Count - 1, i - 1)
Dim nextTxt = txtList2(nextIndex)
Dim prevTxt = txtList2(prevIndex)
Dim testInt As Integer = 0
If thisTxt.Text = "0" Then
thisTxt.Clear()
End If
Next
Dim allTextBoxes = From txt In Me.Panel1.Controls.OfType(Of TextBox)()
Order By txt.TabIndex
Dim txtList = allTextBoxes.ToList()
For i As Int32 = 0 To txtList.Count - 1
Dim thisTxt = txtList(i)
For j = 2 To -1
For k = 1 To 4
thisTxt.Text = worksheet.Cells(i + j, k).Value
Next
Next
Next
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If

Try
myStream = fd.OpenFile()
If (myStream IsNot Nothing) Then
workbook = APP.Workbooks.Open(fd.FileName, ReadOnly:=True, Notify:=False)
worksheet = workbook.Worksheets("sheet1")
...
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (myStream IsNot Nothing) Then
myStream.Close()
End If
If (workbook IsNot Nothing) Then
workbook.Close()
End If
End Try

Make sure the application is closed and no process is running or it will give you that error.

Related

Image.FromStream is not a member of System.Windows.Forms.DataGridViewImageColumn

So I use this code to display my data in a DataGridView:
Sub display_Infodata()
DGUSERS.Rows.Clear()
Dim sql As New MySqlDataAdapter("select * from tbl_info", con)
Dim ds As New DataSet
DGUSERS.AllowUserToAddRows = False
DGUSERS.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
DGUSERS.RowTemplate.Height = 40
sql.Fill(ds, 0)
For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
Dim xx As Integer = DGUSERS.Rows.Add
Dim uid As String = ds.Tables(0).Rows(i).Item(0).ToString
Dim sqls As New MySqlDataAdapter("select * from tbl_other where userid='" & uid & "'", con)
Dim dss As New DataSet
sqls.Fill(dss, 0)
With DGUSERS.Rows(xx)
If dss.Tables(0).Rows.Count > 0 Then
.Cells(0).Value = uid
.Cells(1).Value = ds.Tables(0).Rows(i).Item(2).ToString
.Cells(2).Value = ds.Tables(0).Rows(i).Item(3).ToString
.Cells(3).Value = ds.Tables(0).Rows(i).Item(4).ToString
.Cells(4).Value = ds.Tables(0).Rows(i).Item(5).ToString
.Cells(5).Value = ds.Tables(0).Rows(i).Item(6).ToString
.Cells(6).Value = dss.Tables(0).Rows(0).Item(1).ToString
.Cells(7).Value = ds.Tables(0).Rows(0).Item(2).ToString
.Cells(8).Value = ds.Tables(0).Rows(0).Item(8).ToString
.Cells(9).Value = ds.Tables(0).Rows(0).Item("Image")
.Cells(10).Value = dss.Tables(0).Rows(0).Item(2).ToString
.Cells(11).Value = dss.Tables(0).Rows(0).Item(3).ToString
Else
End If
End With
Next
End Sub
It displays and works, but my problem is that when I try to display the data in the DataGridView of another form it shows the following error:
This is what I use:
Try
With View_Info
Dim index As Integer
Dim selectedRow As DataGridViewRow
selectedRow = DGUSERS.Rows(index)
.UserID.Text = DGUSERS.SelectedRows(0).Cells("UserID").Value
.UserType.Text = DGUSERS.SelectedRows(0).Cells("UserType").Value
.Fname.Text = DGUSERS.SelectedRows(0).Cells("Firstname").Value
.Mname.Text = DGUSERS.SelectedRows(0).Cells("Middlename").Value
.Lname.Text = DGUSERS.SelectedRows(0).Cells("Lastname").Value
.Contact.Text = DGUSERS.SelectedRows(0).Cells("Contact").Value
.Standing.Text = DGUSERS.SelectedRows(0).Cells("Standing").Value
.Guardian.Text = DGUSERS.SelectedRows(0).Cells("Guardian").Value
.ContactG.Text = DGUSERS.SelectedRows(0).Cells("GuardianContact").Value
.DPCreated.Text = DGUSERS.SelectedRows(0).Cells("DateCreated").Value
.DPValidity.Text = DGUSERS.SelectedRows(0).Cells("Validity").Value
Dim img As Byte()
img = DGUSERS.SelectedRows(0).Cells("Image").Value
Dim ms As New MemoryStream(img)
.UploadImage.Image = Image.FromStream(ms)
.Show()
.Focus()
End With
Catch ex As Exception
MsgBox(ex.Message & " Please select a corresponding records.", MsgBoxStyle.Exclamation)
End Try
Any help please?
It's hard to see the full picture, but the problem is most likely that you have created a DataGridViewImageColumn which you've chosen to call Image.
The compiler will always choose local variables, properties or classes over library/pre-imported namespace objects with the same name. Thus, your column by the name Image will be used rather than System.Drawing.Image because the former is "more local".
Try specifying the namespace as well and it should work:
.UploadImage.Image = System.Drawing.Image.FromStream(ms)
So what I did to solve this is by:
Dim pCell As New DataGridViewImageCell
pCell = Me.DGUSERS.Item("Picture", e.RowIndex)
.UploadImage.Image = byteArrayToImage(pCell.Value)
and using this function:
Private Function byteArrayToImage(ByVal byt As Byte()) As Image
Dim ms As New System.IO.MemoryStream()
Dim drwimg As Image = Nothing
Try
ms.Write(byt, 0, byt.Length)
drwimg = New Bitmap(ms)
Finally
ms.Close()
End Try
Return drwimg
End Function

how to search through sub folders vb.net with a windows service?

I'm having problems with my code, the idea is to find a file in a folder but this is a remote folder and it has many sub folders if it doesn't find it then it should look for it in another folder, but it doesn't seem to work could anyone help me please? thanks for any help :).
Dim dt2 As New System.Data.DataTable()
Dim query2 As String = "SELECT juzgado, rutaPDF FROM mismoCorreo WHERE DATEPART(DAY, BirthDate) = #Day AND DATEPART(MONTH, BirthDate) = #Month"
Dim constr2 As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr2)
Using cmd As New SqlCommand(query2)
cmd.Connection = con
cmd.Parameters.AddWithValue("#Day", DateTime.Today.Day)
cmd.Parameters.AddWithValue("#Month", DateTime.Today.Month)
Using sda As New SqlDataAdapter(cmd)
sda.Fill(dt2)
End Using
End Using
End Using
For Each row As DataRow In dt2.Rows
Dim juzgado As String = row("juzgado").ToString()
Dim nombre_archivo As String = row("rutaPDF").ToString()
If (juzgado = "PRIMERO DE LO FAMILIAR") Then
enviar = "\\172.16.20.101\SisInt\Juzgados\acuerdos\J92016SEM2" & "\" & nombre_archivo & ".docx"
ElseIf (juzgado = "SEGUNDO DE LO FAMILIAR") Then
enviar = "\\172.16.20.101\SisInt\Juzgados\acuerdos\J102016SEM2" & "\" & nombre_archivo & ".docx"
End If
Next
For index = 0 To ListaArchivos.Count - 1
Dim wordApplication = New Microsoft.Office.Interop.Word.Application()
Dim wordDocument As Document = Nothing
Dim paramSourceDocPath As String = ListaArchivos.Item(index)
Dim paramExportFilePath As String = "\\172.16.20.101\SisInt\Convertidos" + "\" + ListaNombres.Item(index) + ".pdf"
Dim paramExportFormat As WdExportFormat =
WdExportFormat.wdExportFormatPDF
Dim paramOpenAfterExport As Boolean = False
Dim paramExportOptimizeFor As WdExportOptimizeFor =
WdExportOptimizeFor.wdExportOptimizeForPrint
Dim paramExportRange As WdExportRange =
WdExportRange.wdExportAllDocument
Dim paramStartPage As Int32 = 0
Dim paramEndPage As Int32 = 0
Dim paramExportItem As WdExportItem =
WdExportItem.wdExportDocumentContent
Dim paramIncludeDocProps As Boolean = True
Dim paramKeepIRM As Boolean = True
Dim paramCreateBookmarks As WdExportCreateBookmarks =
WdExportCreateBookmarks.wdExportCreateWordBookmarks
Dim paramDocStructureTags As Boolean = True
Dim paramBitmapMissingFonts As Boolean = True
Dim paramUseISO19005_1 As Boolean = False
Try
'Abrir documento basados en el que selecciono
wordDocument = wordApplication.Documents.Open(paramSourceDocPath)
' Exportar al formato deseado
If Not wordDocument Is Nothing Then
wordDocument.ExportAsFixedFormat(paramExportFilePath,
paramExportFormat, paramOpenAfterExport,
paramExportOptimizeFor, paramExportRange, paramStartPage,
paramEndPage, paramExportItem, paramIncludeDocProps,
paramKeepIRM, paramCreateBookmarks,
paramDocStructureTags, paramBitmapMissingFonts,
paramUseISO19005_1)
End If
Catch ex As Exception
'MessageBox.Show(ex.Message)
'Registro en base de datos fecha hora y ex.message
Finally
If Not wordDocument Is Nothing Then
wordDocument.Close(False)
wordDocument = Nothing
End If
If Not wordApplication Is Nothing Then
wordApplication.Quit()
wordApplication = Nothing
End If
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
End Try
Next

Determine if screen is active or not from Windows 8 Registry

I am looking at monitors list in
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\DISPLAY
In Windows 7, there are a subkey under each screen node named "Control" that indicate if the screen is active or not.
In Windows 8 there are no such subkey.
How can determine if a monitor is active or not from the Windows 8 registry?
Try this code (I verified this):
Public Function GetMonitorDetails() As List(Of WSGetLoginData.Monitor)
'Open the Display Reg-Key
Dim wmiPNPID As New List(Of String)
Dim mc As System.Management.ManagementClass
Dim moc As ManagementObjectCollection
Dim PathPNPID As String
mc = New ManagementClass("Win32_DesktopMonitor")
moc = mc.GetInstances()
For Each mo In moc
PathPNPID = mo.Item("PNPDeviceID")
If PathPNPID.Trim <> "" AndAlso PathPNPID.Contains("\") Then
PathPNPID = PathPNPID.Substring(PathPNPID.LastIndexOf("\") + 1)
wmiPNPID.Add(PathPNPID.ToUpper)
End If
Next
Dim Display As RegistryKey = Registry.LocalMachine
Dim bFailed As [Boolean] = False
Dim obj_ListMonitor As New List(Of WSGetLoginData.Monitor)
Try
Display = Registry.LocalMachine.OpenSubKey("SYSTEM\CurrentControlSet\Enum\DISPLAY")
Catch
bFailed = True
End Try
If Not bFailed And (Display IsNot Nothing) Then
'Get all MonitorIDss
For Each sMonitorID As String In Display.GetSubKeyNames()
Dim MonitorID As RegistryKey = Display.OpenSubKey(sMonitorID)
If MonitorID IsNot Nothing Then
'Get all Plug&Play ID's
For Each sPNPID As String In MonitorID.GetSubKeyNames()
Dim PnPID As RegistryKey = MonitorID.OpenSubKey(sPNPID)
If PnPID IsNot Nothing Then
Dim sSubkeys As String() = PnPID.GetSubKeyNames()
'Check if Monitor is active
'If Array.IndexOf(sSubkeys, "Control") > -1 Then
If Not wmiPNPID Is Nothing AndAlso wmiPNPID.Count > 0 AndAlso wmiPNPID.Contains(sPNPID.ToUpper) Then
If Array.IndexOf(sSubkeys, "Device Parameters") > -1 Then
Dim DevParam As RegistryKey = PnPID.OpenSubKey("Device Parameters")
Dim sSerial As String = ""
Dim sModel As String = ""
'Define Search Keys
Dim sSerFind As New String(New Char() {ChrW(0), ChrW(0), ChrW(0), ChrW(&HFF)})
Dim sModFind As New String(New Char() {ChrW(0), ChrW(0), ChrW(0), ChrW(&HFC)})
'Get the EDID code
Dim bObj As Byte() = TryCast(DevParam.GetValue("EDID", Nothing), Byte())
If bObj IsNot Nothing Then
'Get the 4 Vesa descriptor blocks
Dim sDescriptor As String() = New String(3) {}
sDescriptor(0) = Encoding.[Default].GetString(bObj, &H36, 18)
sDescriptor(1) = Encoding.[Default].GetString(bObj, &H48, 18)
sDescriptor(2) = Encoding.[Default].GetString(bObj, &H5A, 18)
sDescriptor(3) = Encoding.[Default].GetString(bObj, &H6C, 18)
'Search the Keys
For Each sDesc As String In sDescriptor
If sDesc.Contains(sSerFind) Then
sSerial = sDesc.Substring(4).Replace(vbNullChar, "").Trim()
End If
If sDesc.Contains(sModFind) Then
sModel = sDesc.Substring(4).Replace(vbNullChar, "").Trim()
End If
Next
End If
If Not String.IsNullOrEmpty(sSerial) AndAlso sSerial.Trim <> "" Then
Dim insertar As Boolean = True
If Not obj_ListMonitor Is Nothing AndAlso obj_ListMonitor.Count > 0 Then
For k As Integer = 0 To obj_ListMonitor.Count - 1
If obj_ListMonitor(k).SerialNumber.Trim = sSerial Then
insertar = False
Exit For
End If
Next
End If
If insertar Then
Dim obj_monitor As New WSGetLoginData.Monitor
obj_monitor.UUID = Security.FingerPrint.Value(sModel & sSerial)
obj_monitor.Modelo = sModel
obj_monitor.SerialNumber = sSerial
obj_ListMonitor.Add(obj_monitor)
End If
End If
End If
End If
End If
Next
End If
Next
End If
Return obj_ListMonitor
End Function

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

dynamic table and button creation in asp.net

I have created a dynamic table using for loop condition.In which it has a button while i click a specific button it should open a file.But in my coding it is opening a file button in the last row.
If Not IsPostBack Then
txtlogsdate.Text = FormatDate(Now)
End If
Try
trViewlogs.Visible = True
lbllogs.Visible = False
lbllogname.Visible = True
RT1.Visible = False
pb.Visible = False
Dim d1 As DateTime = txtlogsdate.Text
Dim dd As String = d1.ToString("dd")
Dim mm As String = d1.ToString("MM")
Dim yy As String = d1.ToString("yy")
Dim d2 As String = yy & "" & mm & "" & dd
Dim di As DirectoryInfo = New DirectoryInfo(Server.MapPath("~\logs"))
Dim files As FileInfo() = di.GetFiles("*.log")
Dim tab As New Table()
tab.CellPadding = 0
tab.CellSpacing = 0
tab.BorderStyle = BorderStyle.Double
tab.Attributes.Add("style", "margin-left: 0.5px; width: 800px;")
Dim row As New TableRow()
Dim headerCell1 As New TableHeaderCell()
headerCell1.Text = "Logs"
headerCell1.Attributes.Add("style", "margin-left: 0.5px; height: 20px;")
headerCell1.BackColor = System.Drawing.Color.CornflowerBlue
headerCell1.ForeColor = System.Drawing.Color.White
row.Controls.Add(headerCell1)
tab.Controls.Add(row)
Dim headerCell2 = New TableHeaderCell()
headerCell2.Attributes.Add("style", "margin-left: 0.5px; height: 20px;")
headerCell2.BackColor = System.Drawing.Color.CornflowerBlue
headerCell2.ForeColor = System.Drawing.Color.White
headerCell2.Text = "Download"
row.Controls.Add(headerCell2)
tab.Controls.Add(row)
For i As Integer = 0 To files.Length - 1
Dim a As String = files(i).ToString.Replace("Event-", "")
Dim c As String = a.Substring(0, 6)
Dim sw As String
If d2 = c Then
sw = My.Computer.FileSystem.ReadAllText(_
GetWebSitePhysicalRoot & "\logs\" & files(i).ToString)
lbllogname.Text = files(i).ToString
lbllogname.Visible = False
row = New TableRow()
If i Mod 2 = 0 Then
row.BackColor = System.Drawing.Color.White
Else
row.BackColor = System.Drawing.Color.AliceBlue
End If
Dim cell As New TableCell()
cell.Text = lbllogname.Text
'cell.Width = New Unit("1000px")
cell.HorizontalAlign = HorizontalAlign.Center
row.Controls.Add(cell)
Dim cell2 As New TableCell()
Dim bt As New Button
bt.BorderStyle = BorderStyle.Solid
bt.Text = files(i).ToString
AddHandler bt.Click, AddressOf bt_Click
cell2.HorizontalAlign = HorizontalAlign.Center
cell2.Controls.Add(bt)
row.Controls.Add(cell2)
tab.Controls.Add(row)
Panel1.Controls.Add(tab)
End If
Next i
If lbllogname.Text = "" Then
lbllogname.Text = "No Logs to Display !"
End If
Session("pageurl") = ""
Session("pagecount") = ""
ib.SetInfo("Reports > View Logs", Infobar.InfoTypes.Caption)
Dim mi As Integer = GetQueryStringToInt("menuindex", 1)
If Not IsPostBack Then
leftmenu1.AddItem("View Logs", _
GetWebSiteUrlRoot & "/staff_rpt.aspx?rpt=logs&page=1&menuindex=" & mi)
End If
Catch ex As Exception
WriteLog(LogWriter.EventType.eError, ex.StackTrace.ToString)
End Try
Protected Sub bt_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs
Dim a As String
a = lbllogname.Text
Response.ContentType = "text/plain"
Response.AppendHeader("Content-Disposition", "attachment; filename=" & a)
Response.TransmitFile(Server.MapPath("~/logs/" & a))
Response.End()
End Sub
To use the dynamic table structure you have built in your code, then you need to uniquely name each button in each row; otherwise the button click handler (bt_Click) cannot figure out the correct row to open the file in, because they are all called the same and will use the last one.
Since you want a table structure, then I suggest you use the GridView server control, as it will provide similar output, but provide the ability to use templating to name the controls of each row the same, but allow for you to differentiate individual rows when a click event happens.