Delete a file in use by another process in vb.net / framework 2.0 - vb.net

I have a program that watches if there is a file with a certain name, in a certain directory.
the FileStream is created with the sequent command:
fs = File.Open(PathK, FileMode.Append, FileAccess.Write, FileShare.None)
After half an hour, the program closes, disposes and kills the text file and then shuts down itself, calling for another program to create another process of itself and closes the old one.
Sometimes this doesn't happen though. The file can't be removed and it causes an error.
After that the program closes itself and continues with its restart routine. but when it starts itself, it checks if there is that specific file, and there it is, because it couldn't kill it. Now, i can do File.OpenRead on that file, so the old filestream of the old process is not running, so it means the old one process is shut down. But I still can't kill it!
this is the starting code:
Private Sub Verifica_PID_Aperti()
Dim Tentativi As Integer = 0
PidAlreadyOpen = 0
'file exist ?
If File.Exists(PathK) = True Then
Try
'can i read it?
File.OpenRead(PathK)
Catch ex As Exception
'if it's locked than there is another PID active right now, stop this process
Settaggi.lStop = 1
PidAlreadyOpen = 1
Exit Sub
End Try
'not locked? than it's a bug and the file is still open, try to delete
While (Tentativi < 1000)
Try
File.Delete(PathK)
Tentativi = 1000
Catch ex As Exception
Tentativi = Tentativi + 1
End Try
End While
'is him still alive?
If File.Exists(PathK) Then
'if yes, there is an error, sand a mail and close yourself
Dim pf As New Send_Mail
pf.Invio_Mail_Automatico_EDP(999, "ERRORECHIUSURA", Err.Description & " - " & PathK, "", Settaggi.lPID)
pf = Nothing
Settaggi.lStop = 1
PidAlreadyOpen = 1
Exit Sub
Else
'ok, if it does not exists anymore, create another one
fs = File.Open(PathK, FileMode.Append, FileAccess.Write, FileShare.None)
End If
Else
'no file ? than create it
fs = File.Open(PathK, FileMode.Append, FileAccess.Write, FileShare.None)
End If
End Sub
and here it's the code for the restart procedure:
If PidAlreadyOpen = 0 Then
'close and clean
fs.Close()
fs.Dispose()
End If
Threading.Thread.Sleep(1000)
Dim Chiusura As Integer = 0
While Chiusura < 1000
Try
'try to delete
File.Delete(PathK)
If TimeToReboot = 1 Then
System.Diagnostics.Process.Start(Application.ExecutablePath, "/noservice /release /PID:" & Settaggi.lPID)
End If
Catch ex As Exception
Chiusura = Chiusura + 1
' not deleted ? send an email, and don't stop yourself
If Chiusura = 999 Then
Dim pf As New Send_Mail
pf.Invio_Mail_Automatico_EDP(999, "ERRORECHIUSURA", Err.Description & " - " & PathK, "", Settaggi.lPID)
pf = Nothing
Exit Sub
End If
Threading.Thread.Sleep(100)
End Try
'deleted? than stop the loop
If Not File.Exists(PathK) Then
Chiusura = 1000
End If
End While
Me.Close()
how do you think should i resolve this problem ?

I don't think there's much you can do here. I had similar issues in the past and found that, while it's not possible to delete the file, it is possible to rename the file. Depending on the situation, you can rename the file and open a new file with that name. You'll also need to check, later in the process, if the renamed file is still used and delete it.

Related

vb.net cannot find file after file has been deleted and resaved by remote pc

I'm using a web page to create a file on a web server to control an Arduino device. The file gets created without issue. The problem exists when the VB app that controls the Arduino device reads the file and then deletes the file. After VB deletes the file the web app recreates the same file with new data. The VB app fails to see the new file. It still thinks the file has been deleted.
Here's the code:
Private Sub TimerCheck4CameraFile_Tick(sender As Object, e As EventArgs) Handles TimerCheck4CameraFile.Tick
Try
' Check if file exists if it doesn't leave this method.
Dim DirectoryList As New IO.DirectoryInfo("C:\inetpub\wwwroot")
Dim ArrayOfFilesFileInfo As IO.FileInfo() = DirectoryList.GetFiles("ServoDirection2Move.txt")
Dim Fi As IO.FileInfo
For Each Fi In ArrayOfFilesFileInfo
If String.Compare("ServoDirection2Move.txt", Fi.Name) <> 0 Then
TextBox1.Text += vbCrLf + "Did NOT Find File."
Exit Sub ' We DID NOT find the file so get out!
End If
Next
Catch ex As Exception
LabelStatus.Text = "Catch ex 1: " + ex.Message
End Try
' Read in the file.
Dim FileRead As String
Try
' **POSSIBLE ISSUE HERE**.
FileRead = My.Computer.FileSystem.ReadAllText("C:\inetpub\wwwroot\ServoDirection2Move.txt")
' Need better way to read txt file. It fails after file is deleted and can not read second file.
TextBox1.Text += vbCrLf + "Moving Value: " + FileRead
Catch ex As Exception
LabelStatus.Text = "Catch ex: " + ex.Message
End Try
' Check if it was UP.
If String.Compare("UP", FileRead) = 0 Then
' Delete the file to prepare for a new one.
System.IO.File.Delete("C:\inetpub\wwwroot\ServoDirection2Move.txt")
' Move servo to proper location.
Call PanningUp.PerformClick()
LabelStatus.Text = "Done Moving: UP" ' Update Status Bar.
TimerCheck4CameraFile.Enabled = True ' Turn timer back on.
Exit Sub
End If

Wait for a specefic program to open before continue VB.NET

Alright, as you see in the code down below I've got a simple try statement.
Whenever I open the tool it will look for a process named csgo, if there is a process it will continue with the tool else it will just send a MsgBox and exit the tool.
However, I want it for it to check if there is a csgo process running, if it's running it should continue like it is now, but if there isn't a process named csgo running I'd like to make the tool Sleep and loop til it finds a process named csgo.
Try
gameProcess = Process.GetProcessesByName("csgo")(0)
gameHandle = OpenProcess(PROCESS_ALL_ACCESS, False, csgoProcess.Id)
Catch ex As Exception
MsgBox("Please Start CS:GO before opening this tool")
Environment.Exit(0)
End Try
I tried doing like this, and it works lol, is there a better way of doing this?
Dim Found = 0
While Found = 0
Try
gameProcess = Process.GetProcessesByName("csgo")(0)
cgameHandle = OpenProcess(PROCESS_ALL_ACCESS, False, csgoProcess.Id)
Found = 1
Catch ex As Exception
MsgBox("Waiting for csgo to launch.")
Threading.Thread.Sleep(1000)
End Try
End While
Assuming this is a console application, you can make some improvements over what you have.
' Use a boolean for binary logic.
' This takes up 1 bit whereas your Int32 took up 32 bits
Dim allDone = False
While Not allDone
Try
Dim processes = Process.GetProcessesByName("csgo")
If processes.Count > 0 Then
csgoProcess = processes(0)
Dim handle = OpenProcess(PROCESS_ALL_ACCESS, False, csgoProcess.Id)
If handle IsNot Nothing Then
allDone = True
End If
Else
' Use a Retry / Cancel MsgBox to allow the user to retry or cancel
' Clicking Cancel will now exit the application
Select Case MsgBox("Waiting for csgo to launch.",
MsgBoxStyle.RetryCancel, "Confirm retry")
Case MsgBoxResult.Retry
Threading.Thread.Sleep(1000)
Case MsgBoxResult.Cancel
Environment.Exit(0)
End Select
End If
Catch ex As Exception
' Something bad happened, but you don't know what exactly.
' You should exit, else it might keep happening
MsgBox("Your application encountered the following error and will now close: " _
& ex.Message)
Environment.Exit(0)
End Try
End While
' continue application

Many instances of the same process writing to the same log file

I am kicking off a number of instances of the same process and the issue is that they all write to the same log file. I know it is not a good practice and was wondering what can I do to avoid possible issues. Here is the procedure I use to write to file:
Sub WriteToErrorLog(ByVal Msg As String)
Dim path As String
path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
Dim strFile As String = System.IO.Path.Combine(path, "Log_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt")
Dim sw As StreamWriter
Dim fs As FileStream = Nothing
Try
If (Not File.Exists(strFile)) Then
fs = File.Create(strFile)
fs.Close()
End If
sw = File.AppendText(strFile)
sw.WriteLine(Msg & vbcrlf)
Catch ex As Exception
MsgBox("Error Creating Log File")
MsgBox(ex.Message & " - " & ex.StackTrace)
Finally
sw.Close()
End Try
End Sub
I would appreciate any suggestions/improvements. thanks!
As I have said in my comment, the scenario of multiple access to the same file resource should be handled carefully and probably the best solution is to use a well tested log library like Log4Net or NLog.
In any case you could improve your code in a couple of point
Sub WriteToErrorLog(ByVal Msg As String)
Dim path As String
path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
Dim strFile As String = System.IO.Path.Combine(path, "Log_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt")
Dim retry as Integer = 3 ' this could be changed if you experience a lot of collisions.'
Dim sw As StreamWriter = Nothing
While retry > 0
Try
Using sw = File.AppendText(strFile)
sw.WriteLine(Msg & vbcrlf)
End Using
Exit While
Catch ex as Exception
retry -= 1
End Try
End While
' If retry has reached zero then we have exausted our tentatives and give up....'
if retry = 0 Then
MessageBox.Show("Error writing to Log File")
End if
End Sub
I have removed all the part that check if file exists and then create it. This is not necessary because as the documentation explains, File.Append is the same that calling StreamWriter(file, true) and this means that if the file doesn't exist it will be created.
Next, to try to handle possible collision with other process writing to the same file concurrently, I have added a retry loop that could get access to the log file just after another process finishes.
(this is really a poor-man solution but then it is better to use a well tested library)
It is important to enclose the opening and writing of the file inside a using statement that closes and disposes the Stream also in case of exceptions. This is mandatory to be sure to leave the file always closed for the other processes to work.

PC cannot print to Email using Outlook

I am having a very strange problem where one of the computers in our company is unable to print an MS Access report and attach it to an email. I have done a lot of research however most of it doesn't apply to my case as this issue is happening only on one PC out of the 20+ we have in the company. This is a print screen of the error we are getting:
The code I am using is the following:
If PrintMode = "Email" Then
Dim mAcc As New Access.Application
Dim DefaultPrinterName As New String("")
Dim PDFPrinterName As New String("")
Maintain__Loading.Setup()
Try
mAcc.CloseCurrentDatabase()
mAcc.DoCmd.Close()
System.Runtime.InteropServices.Marshal.ReleaseComObject(mAcc)
mAcc = Nothing
Catch ex As Exception
End Try
Dim startInfo As New ProcessStartInfo("C:\Program Files (x86)\PDFCreator\PDFCreator.exe") 'starts PDF Creator so it can save the report to PDF
startInfo.WindowStyle = ProcessWindowStyle.Minimized
Process.Start(startInfo)
AttachmentName = "C:\PDFs\pdf.pdf" 'PDF has been set up to save all files as TestPrint.pdf
PDFPrinterName = "PDFCreatorDistribution"
'------ GETS DEFAULT PRINTER NAME -------
Dim oPS As New System.Drawing.Printing.PrinterSettings
Try
DefaultPrinterName = oPS.PrinterName
Catch ex As System.Exception
DefaultPrinterName = ""
Finally
oPS = Nothing
End Try
'sets PDFCreatorDistribution as default printer
Shell(String.Format("rundll32 printui.dll,PrintUIEntry /y /n ""{0}""", PDFPrinterName))
Try
If Not UCase(Trim(Database)) = "TEST" Then
mAcc.OpenCurrentDatabase("R:\Distribution\Access\Distribution-Reports.mde")
Else
mAcc.OpenCurrentDatabase("R:\Distribution\Access\Test-Distribution-Reports.mde")
End If
Catch ex As Exception
MsgBox(Err.Description)
End Try
If IO.File.Exists(AttachmentName) Then 'if file exists it deletes it
IO.File.Delete(AttachmentName)
End If
Select Case Trim(Grid.Rows(Grid.CurrentRow.Index).Cells("Passing1Type").Value.ToString)
Case "String"
mAcc.DoCmd.OpenReport(Trim(Grid.Rows(Grid.CurrentRow.Index).Cells("MacroName").Value.ToString), Access.AcView.acViewPreview, , Trim(Grid.Rows(Grid.CurrentRow.Index).Cells("Passing1").Value.ToString) & " = '" & Number & "'", Access.AcWindowMode.acWindowNormal)
Case "Numeric"
mAcc.DoCmd.OpenReport(Trim(Grid.Rows(Grid.CurrentRow.Index).Cells("MacroName").Value.ToString), Access.AcView.acViewPreview, , Trim(Grid.Rows(Grid.CurrentRow.Index).Cells("Passing1").Value.ToString) & " = " & Number & "", Access.AcWindowMode.acWindowNormal)
End Select
mAcc.DoCmd.PrintOut()
mAcc.Visible = True
mAcc.CloseCurrentDatabase()
mAcc.DoCmd.Close()
System.Runtime.InteropServices.Marshal.ReleaseComObject(mAcc)
mAcc = Nothing
Do While Not System.IO.File.Exists("C:\PDFs\pdf.pdf")
Threading.Thread.Sleep(2000) 'if doesn't exist, wait for 2 seconds
If Not System.IO.File.Exists("C:\PDFs\pdf.pdf") Then 'if doesn't exist, wait for another 2 seconds
Threading.Thread.Sleep(2000)
End If
If Not System.IO.File.Exists("C:\PDFs\pdf.pdf") Then 'if doesn't exist, wait for another 2 seconds
Threading.Thread.Sleep(2000)
End If
If Not System.IO.File.Exists("C:\PDFs\pdf.pdf") Then 'shows error message
MsgBox("Error creating PDF. Please try again")
Exit Do
End If
Loop
'sets default printer name
Shell(String.Format("rundll32 printui.dll,PrintUIEntry /y /n ""{0}""", DefaultPrinterName))
'saves file as
Dim saveFileDialog As New SaveFileDialog()
saveFileDialog.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*"
If saveFileDialog.ShowDialog() = DialogResult.OK Then 'if OK clicked
FileName = saveFileDialog.FileName 'get file name and move to new location/name
FileNameOnly = System.IO.Path.GetFileName(FileName)
Try
If IO.File.Exists(FileName) Then 'if file exists it deletes it before saving
IO.File.Delete(FileName)
End If
IO.File.Move(AttachmentName, FileName)
Catch ex As Exception
MsgBox(Err.Description)
Finally
Shell(String.Format("rundll32 printui.dll,PrintUIEntry /y /n ""{0}""", DefaultPrinterName))
End Try
Else 'user clicked cancel
FileName = ""
End If
Maintain__Loading.Dispose()
'GETS TO HERE AND AFTER THIS I GET THE ERROR MESSAGE DISPLAYED IN THE IMAGE ABOVE
If IO.File.Exists(FileName) Then
Try
Send_Email()
Catch ex As Exception
MsgBox(Err.Description)
End Try
Else
If Not FileName = "" Then MsgBox("An error has occured. Please try again")
End If
Shell(String.Format("rundll32 printui.dll,PrintUIEntry /y /n ""{0}""", DefaultPrinterName))
PhysicallyPrintedOrEmailed = True
End If 'Printmode = Email
I found a thread that I thought would solve my problem however unfortunately it didn't:
Unable to cast COM object - Microsoft outlook & C#
Any advice will be greatly appreciated
You have hardcoded the path to the program files location so if you are running this on a 32 bit machine it won't find the PDFCreator.exe.
Use Environment.GetFolderPath to find the path on the machine instead of hard coding it.`
Also it might help if you wrap the whole thing in a Try Catch block to see if there is an error somewhere you didn't expect
I have managed to solve this. Probably not the best way but we reinstalled Outlook and this solved the issue. We believe another program (most likely one that syncs Outlook contacts with phone) that has been installed has corrupted something. Thanks anyway :)

ASP.NET How do I wait for file upload/release?

I've got ASP.NET intranet application written in VB. It gets a file from the user, and then depending on a few different cases it may create a few copies of the file as well as move the original.
Unfortunately I've come across a case where I get this error:
Exception Details: System.IO.IOException: The process cannot access the file
'\\some\dir\D09_03_5_180_0.000-6.788.png' because it is being used by
another process.
Which is thrown by My.Computer.FileSystem.CopyFile. And that's fine that it's being used by another process - it may still be saving/downloading from the user or trying to copy while another thread(?) is copying, I don't really care about that, what I want to know:
Is there any way that I can tell VB to wait to copy (also move) the file until the file is no longer in use?
Thanks
Test if the file is in use and the do what you need to do.
Public Sub WriteLogFile(ByVal pText As String, ByVal psPath As String, ByVal psName As String)
Dim strFullFileName As String
Dim Writer As System.IO.StreamWriter
Dim Fs As System.IO.FileStream
Try
Dim DirectoryHandler As New System.IO.DirectoryInfo(psPath)
strFullFileName = psPath & "\" & psName & Date.Today.Month.ToString & "-" & Date.Today.Day.ToString & "-" & Date.Today.Year.ToString & ".txt"
If Not DirectoryHandler.Exists() Then
Try
Monitor.Enter(fsLocker)
DirectoryHandler.Create()
Finally
Monitor.Exit(fsLocker)
End Try
End If
Try
If CheckIfFileIsInUse(strFullFileName) = True Then
Thread.Sleep(500) ' wait for .5 second
WriteLogFile(pText, psPath, psName)
If Not Fs Is Nothing Then Fs.Close()
If Not Writer Is Nothing Then Writer.Close()
Exit Sub
End If
Monitor.Enter(fsLocker)
Fs = New System.IO.FileStream(strFullFileName, IO.FileMode.Append, IO.FileAccess.Write, IO.FileShare.Write)
Writer = New System.IO.StreamWriter(Fs)
Writer.WriteLine(Date.Now.ToString & vbTab & "ProcessID: " & Process.GetCurrentProcess.Id.ToString() & vbTab & pText)
Writer.Close()
Fs.Close()
Finally
Monitor.Exit(fsLocker)
End Try
Catch ex As Exception
Dim evtEMailLog As System.Diagnostics.EventLog = New System.Diagnostics.EventLog()
evtEMailLog.Source = Process.GetCurrentProcess.ProcessName.ToString()
evtEMailLog.WriteEntry(ex.Message, System.Diagnostics.EventLogEntryType.Error)
Finally
If Not Fs Is Nothing Then Fs.Close()
If Not Writer Is Nothing Then Writer.Close()
End Try
End Sub
Public Function CheckIfFileIsInUse(ByVal sFile As String) As Boolean
If System.IO.File.Exists(sFile) Then
Try
Dim F As Short = FreeFile()
FileOpen(F, sFile, OpenMode.Append, OpenAccess.Write, OpenShare.Shared)
FileClose(F)
Catch
Return True
End Try
End If
End Function
Hmm... not directly.
What most implementations are doing, is making a retry of copying the file, with a small timeframe (some seconds)
if you want to make a nice UI, you check via Ajax, if the copying process went well.
Well, it turns out that waiting would not work in this case:
When trying to copy a file you cannot copy a file from one location to the same location or it will throw an error (apparently). Rather than just pretending to copy the file, VB actually tries to copy the file and fails because the copy operation is trying to copy to the file it's copying from (with overwrite:=True at least).
Whoops!