tags:

views:

92

answers:

3

Would anyone know if when you catch an UnauthorizedAccessException in C# its possible to access the path that threw it? I dont want the error message just the path that caused the problem. The try catch block I have could catch on a number of different ones but I need to report it it and continue on to the next directory/file without adding the entire exception message.

+1  A: 

In the Message property of the UnauthorizedAccessException, you'll see something like this:

Access to the path 'E:\Domains\xxx\wwwroot\Images\main.aspx' is denied.

You can parse the path out of this Message.

Keltex
This approach is likely to cause problems with portability, localization and possibly newer versions of the .net framework.
marklam
Yeah I considered doing this however I thought that since the exception message is static and its simply adding a variable to the message there might be some method of accessing that variable directly instead of parsing it so I figured I check first if that was possible.
Trotts
+4  A: 

Maybe make your error handling more granular so you are only catching a single attempt when it blows up? You could do this (without repeating yourself) by refactoring the offending code out to a utility method - i.e.

TryCopyFile(path1);
TryCopyFile(path2);
TryCopyFile(path3);

Where TryCopyFile catches the exception and logs the (single) path that was passed as an argument.

Marc Gravell
Took your advise on this and made the error handling more granular
Trotts
A: 

Keltex is right, catch the UnauthorizedAccessException and parse the Message.

Khan