473,405 Members | 2,154 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Catch if File not Found

Hello, I'm writing a Visual Basic.net (vb.net 03) program and I'm
checking if file(s) exist in a particular directory. If the program
finds such files, I will write the total and names in my log and keep
going. Otherwise, If I find none, I need to write that in my log and
exit the program.

My problem lies when there's no files in that the directory. I can
only get the total (0), but that doesn't get caught as an exception. I
tried different exceptions, but I guess the fact that there are no
files doesn't cause an exception. This is what I have:

Imports System.IO
Imports System.Text
Dim sw As New StreamWriter("c:\mylog.log", True)
Try
' Only get files that have extension *.txt
Dim dirs As String() =
Directory.GetFiles("c:\MyTextFilesDir\", "*.txt")
sw.WriteLine("The number of files with an *.txt extension
is {0}.", dirs.Length)
Dim dir As String
For Each dir In dirs
sw.WriteLine(dir)
Next

Catch ex As FileNotFoundException ' <= I need to modify this!
sw.WriteLine("The process failed: {0}", ex.ToString())
sw.WriteLine("")
sw.WriteLine("Unable to get text file name.")
Exit Sub
End Try
sw.Flush()
sw.Close()

Does anyone knows how to catch when there's no files in a dir and make
that as an exception? Or.. do I need to catch exceptions, or just
check if the total exisinting files = 0?

Thanks

JR.

Mar 27 '06 #1
4 1978
Also, is there a way to get only the filename.extension when the
program finds the text files? Right now it's writing the whole path. I
only need "filename.txt"

Mar 27 '06 #2
It will not throw an exception if the directory is empty instead an
empty collection is returned if no files matching the specified pattern
are found. You can look at the length of your dirs array. Also to get
just the name of the file you can use FileInfo and grab the Name
property.

Dim sw As New StreamWriter("c:\mylog.log", True)
Try
' Only get files that have extension *.txt
Dim dirs As String() =
Directory.GetFiles("c:\MyTextFilesDir\", "*.txt")
If dirs.Length <> 0 Then
sw.WriteLine("The number of files with an *.txt
extension is {0}.", dirs.Length)
Else
sw.WriteLine("The number of files with an *.txt
extension is 0.")
End If
Dim dir As String
For Each dir In dirs
Dim file As New FileInfo(dir)
sw.WriteLine(file.Name)
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
sw.Flush()
sw.Close()
sw = Nothing
End Try

Mar 27 '06 #3
It will not throw an exception if the directory is empty instead an
empty collection is returned if no files matching the specified pattern
are found. You can look at the length of your dirs array. Also to get
just the name of the file you can use FileInfo and grab the Name
property.

Dim sw As New StreamWriter("c:\mylog.log", True)
Try
' Only get files that have extension *.txt
Dim dirs As String() =
Directory.GetFiles("c:\MyTextFilesDir\", "*.txt")
If dirs.Length <> 0 Then
sw.WriteLine("The number of files with an *.txt
extension is {0}.", dirs.Length)
Else
sw.WriteLine("The number of files with an *.txt
extension is 0.")
End If
Dim dir As String
For Each dir In dirs
Dim file As New FileInfo(dir)
sw.WriteLine(file.Name)
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
sw.Flush()
sw.Close()
sw = Nothing
End Try

Mar 27 '06 #4
Hello Mr. Doles, Thanks for replying. I had a similar idea about
checking the number of files with an IF statement, so it's quite nice
to know I'm in the right track.

The fileinfo property works like a charm. Thanks for that too.

JR

Mar 27 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Kim Haines | last post by:
I need help finding where an error is occuring in my code. I use a try-catch block like this in my global.asa: try { //my code } catch (e) { Application('errormsg') = ("An exception...
5
by: Doug Gifford | last post by:
WROX "Beginning VB.Net" 2nd Edition Using this code from Chapter 11 Page 472: Do Try ' Read a line from the file... currentLine = myReader.ReadLine lineCounter = lineCounter + 1 Catch e As...
11
by: l.woods | last post by:
I want to set up my CATCH for a specific exception, but I really don't know which one of the multitude that it is. I am getting the exception now with Catch ex as Exception but I want to be...
5
by: Patrick Dickey | last post by:
Hello, All! I'm modifying some source code that I downloaded from Planet-source-code a while back, and have a question about Try Catch statements. Basically, I'm wondering if I can do a Try with...
32
by: cj | last post by:
Another wish of mine. I wish there was a way in the Try Catch structure to say if there wasn't an error to do something. Like an else statement. Try Catch Else Finally. Also because I...
4
by: j.t.w | last post by:
Hi everyone, I am trying to error trap for an invalid file name. When an invalid file name is given, a message box saying "Cannot find 'file:///F:/Invoice/111.tif'. Make sure the path of...
3
by: Doug | last post by:
Hi i have a method that returns a value public bool readxml (string xmlFilename, out string value) but I would like to catch an exception if it occurs in the method . How do i catch the...
22
by: Amali | last post by:
I'm newdie in c programming. this is my first project in programming. I have to write a program for a airline reservation. this is what i have done yet. but when it runs it shows the number of...
1
by: aemado | last post by:
I am trying to read in several lines, each should have exactly 5 pieces of data. I am using try/catch/throw to determine if the data is in the correct format, and trying to use iss to separate the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.