tags:

views:

22

answers:

2

Hi, I've been tasked to code a little app in c# which searches a directory for a given filetype. I am testing with .txt files, but the app is intended for .epl files for Zebra printers.

I am trying to write it in such a way that:

aO If .epl file is found, send to Printer, delete .epl file then wait a few seconds. Search directory again for .epl file, send to printer, delete.

If .epl file is not found, wait a few seconds, repeat until .epl file is found. Repeat a)

The problem arises when Directory.GetFiles(@s1, "*.txt") finds no .txt files at all and tries to run along with the rest of the program.

I get: System.IndexOutOfRangeException: Index was outside the bounds of the array.

I'm not sure what to do, I believe it's to do with null exceptions? My code is not complete as this problem has me stumped; I'm also a novice and so it's not the cleanest of code.

Code as follows: http://pastebin.com/BHNAtTsk

+2  A: 

You're indiscriminately using filePaths[0] even though the array may be empty. It's not actually to do with null values at all. GetFiles() always returns an array, but it will be an empty array if no matching files are found.

I believe you should simply change your condition to:

if (filePaths.Length > 0)
Jon Skeet
Simple solution, worked no problems. Thanks!I need my morning coffee :p
Nemekh
A: 

Take a look at this code:

string[] filePaths = Directory.GetFiles(@s1, "*.txt");
if ((filePaths[0]).Length > 1)   .....

From the documentation:

http://msdn.microsoft.com/en-us/library/07wt70x2.aspx

If there are no files, this method returns an empty array.

So the appropriate check is instead:

if (filePaths.Length > 0)
pygorex1