How to detect if file isn't found - vb.net

I'm a bit new to VB.NET. I was wondering if there was a way to detect if a file being open doesn't exist, then something will happen. Is this possible and is it possible using the "If" statement?

You can use file.exists(filename) to check before you open it, or a try-catch block:
If not System.IO.File.Exists(filename) Then
' file does not exist
end if
or
Try
open ...
Catch ex As Exception
MsgBox(ex.Message) ' not-found error handling goes here
End Try
You can add imports system.io at the top of your file to use File.Exists instead of System.IO.File.Exists.

Related

writeToFile.WriteLine backspace?

I want to write some text to a .txt file, this is what I have, and it works mostly:
If System.IO.File.Exists(sListItems) = True Then
Dim writeToFile As New System.IO.StreamWriter(sListItems, True)
writeToFile.WriteLine(vbCrLf & txtGameTitle.Text)
writeToFile.Close()
Else
MsgBox("Error!")
End If
End If
The problem is with that, when I enter text such as 'Hello', it would instead put into the txt file 'Hello ' (with a space). Is there anyway to resolve this?
Don't use File.Exists(). It's a race condition waiting to blow up, and it's slower. Instead, look for the FileMode that matches how you want to use the file; then handle the exception if it fails (you need to handle the exception anyway, because of the race condition potential mentioned earlier).
Additionally, if you have your Using blocks correct, you don't need to call .Close().
Try
Using fs As New FileStream(sListItems, FileMode.Open)
fs.Seek(0, SeekOrigin.End)
Using sw As New StreamWriter(fs)
sw.WriteLine(txtGameTitle.Text)
End Using
End Using
Catch ex As IOException
MsgBox("Error! -- " & ex.Message)
End If
But I wonder if you really care that the file already exists, and all you really need to do is this:
File.AppendAllText(sListItems, txtGameTitle.Text)
Well, I think I figured it out. I changed:
writeToFile.WriteLine()
to
writeToFile.Write()
and it no longer gives spaces.
Edit:
I know what my problem was, I was using lbGameList.SelectedItem.ToString() to find the name and it was giving me spaces, so I added .TrimEnd to it and it works now, thanks

Testing if I have full read/write access to a file in VB .NET 4.5 before processing it

I'm writing a windows service which runs as the local system account. I'm trying to make sure if I have full read/write access to a file beginning to process it any further. Here is my code:
Dim FullPath As String
FullPath = "C:\directory\file.txt"
Dim ps As Security.PermissionSet
ps = New Security.PermissionSet(Security.Permissions.PermissionState.Unrestricted)
ps.AddPermission(New Security.Permissions.FileIOPermission(Security.Permissions.FileIOPermissionAccess.AllAccess, FullPath))
ps.AddPermission(New Security.Permissions.FileIOPermission(Security.Permissions.FileIOPermissionAccess.AllAccess, IO.Path.GetDirectoryName(FullPath)))
Try
ps.Demand()
Catch ex As Security.SecurityException
System.Diagnostics.EventLog.WriteEntry("ShopLink", "File " + FullPath + " will not be parsed. " + ex.Message)
Exit Sub
Catch ex As Exception
System.Diagnostics.EventLog.WriteEntry("ShopLink", "File " + FullPath + " will not be parsed. " + ex.Message)
Exit Sub
End Try
Then I set the full access permissions for the file to "Deny" for the user account my service is running as. After executing, the code above doesn't throw any exceptions and allows file processing to begin. When the service later tries to change and/or delete the file, I get an "Access Denied" exception.
Any suggestions?
For this purpose i use thise small function:
Private Function HasAccess(ByVal ltFullPath As String)
Try
Using inputstreamreader As New StreamReader(ltFullPath)
inputstreamreader.Close()
End Using
Using inputStream As FileStream = File.Open(ltFullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
inputStream.Close()
Return True
End Using
Catch ex As Exception
Return False
End Try
End Function
In your case then:
If HasAccess(FullPath) ...
I have solved the problem by using My.Computer.FileSystem.DeleteFile to delete the file instead of Kill. My.Computer.FileSystem.DeleteFile was executed without problems after successfully demanding full read/write access to the file in the way described above, while Kill consistently threw an "Access denied" exception.
Using "Kill"... I know this is a very old thread but I'll add this in case anyone stumbles on it like I did. I was working on some old VB6 legacy code. One of my clients users was getting a runtime exception during a file open after a kill. The code was "Killing" the file and then rebuilding it from scratch with binary data held in memory. It tuns out that the "Kill" function triggered the user's anti-virus software which locked the file long enough to cause the next "Open" statement to fail. I discovered this using an error logging utility (the name escapes me at the moment). The line in the error log file on the failed "Open" statement was that the file's status was "Delete pending" due to the user's anti-virus software.

Finding specific Exceptions using Visual Studio

I'm using VS 2010 Express for VB.net and wondering if there is an easy way to discover exceptions that I might encounter by using the IDE?
For example if I have the following:
If Me.saveQueryDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
Try
sqlTextBox.SaveFile(saveQueryDialog.FileName)
Catch ex As Exception
MessageBox.Show(String.Format("Save was unsuccessful encountered: {0}", ex.Message))
End Try
End If
Can I use the IDE to somehow find that the usual exception I'll encounter in this circumstance is ...ex As IO.IOException
Or in the following:
If Me.openQueryDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
Try
sqlTextBox.LoadFile(openQueryDialog.FileName)
Catch ex As Exception
MessageBox.Show(String.Format("Open was unsuccessful encountered: {0}", ex.Message))
End Try
End If
..the most common exception I'll encounter is ...ex As IO.FileLoadException
Or do I need to just try to remember these specific exceptions?
You can check the MSDN Documentation for each method that you are using to see any possible exception they can throw.
This, for example, are the possible exceptions for .SaveFile() method.

ftp connection and upload what happens to connection if there is exception

Below is code for how you can upload a file using ftp. My question is what happens if there is an exception in the try, will the ftp connection automatically close in the catch? Is it better to use a "using"?
thank you
Try
'connect to ftp server
Dim ftp As New FTPConnection
ftp.ServerAddress = "ftp.example.com"
ftp.UserName = "example_user"
ftp.Password = "example_pass"
ftp.Connect()
ftp.TransferType = FTPTransferType.BINARY
'upload a file
ftp.UploadFile("s:\test.txt", "test.txt")
'close the connection
ftp.Close()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
When an exception happens (whatever it is) the control flow skips everything until it arrives to a Catch instruction.
So in this case if you have an exception in the UploadFile you will not close the connection.
If the FTPConnection class is IDisposable then your best option is to use the using keyword. Otherwise use the finally statament after the Catch as Grant said.
No, it won't close if an exception occurs before ftp.Close() has finished executing. You should use a Finally block to make sure that ftp is always closed, even if an exception occurs. This means you should define ftp at a higher scope level than within the try block, so that it is accessible within the finally block. You could technically call Close from within the catch block but that A) won't cover both/all circumstances and B) might not work anyway if code in the catch throws yet another exception.
Dim ftp As New FTPConnection
Try
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
Finally
ftp.Close()
End Try

Deleting a file causes an untrapable error

In my app i have to copy and then delete image files from memory cards, the problem comes when some of the card inadvertantly have the "Lock" switch engaged turning them to read only.
When trying to delete these files i want to log the failure to delete but not show any UI messages until a time of my choosing.
Here is some sample code i am having trouble with.
Sub Main()
Try
System.IO.File.Delete("K:\BYZTCSQ_0050.JPG")
Catch ex As Exception
'Error would be logged here
End Try
End Sub
This works fine when debuging i.e. it tries to delete the file and if not the error is caught and i can proccess it as nessecary, but when i build and run the app i get an error message telling me that the file cannot be deleted.
To test this code you will need a drive that can be physically set to read only (USB memory key, SD card) and try to delete a file on it while debuging and after a build.
Why would the same code run differently and how can i stop the excess error messages?
You can try to create a file on the memory card. For reasons only known to Microsoft (or not), creating a file on a copy-protected drive will raise the error condition in the Try block while deleting a file will not. Incidentally, I got the same odd result -- catching the delete worked fine in debug mode, but not from the .exe.
Imports System.IO
...
Try
fs = File.Create(drive & "\tmp.~tmp")
Catch ex As Exception
copyprotected = true
End Try
if not copyprotected then
file.delete(drive & "\tmp.~tmp")
file.delete(the file you wanted to in the first place)
end if
Instead of wrapping it in a try/catch block, test to see if the file exists before trying to execute the delete:
Dim strFilePath as String = "K:\BYZTCSQ_0050.JPG"
If File.Exists(strFilePath) Then
System.IO.File.Delete(strFilePath)
End If