Why can't I use the 'AccessDeniedException' namespace? - c#

I get the message that the namespace can't be found when I use the code below. Where does the AccessDeniedException live?
try { ... }
catch (SomeKindOfException ex)
{
MessageBox.Show(ex.Message);
}
catch (AccessDeniedException ex)
{
//Do something else
}
Thanks

I don't think that's the exception you're looking for. The only one with this name (that I can find) is in a Sharepoint namespace. Try attaching the debugger and seeing exactly what the type of the thrown exception is.
The type of the exception is going to vary depending on your context. So for example, if it's an "access denied" when trying to open a file, it could be a FileLoadException, or something similar. If it's encountered because of Code Access Security, it will be SecurityException. And so on.

You may need to give the full namespace on the exception, or have a using statement at the top of your code file so .NET knows where to find the exception you're talking about. If that doesn't work, maybe you need to add the DLL that contains that exception to the "REFERENCES" list in your project.

Related

Directory.Delete - how to tell if folder was not empty vs some other error?

I'm trying to delete a folder only if it's not empty. So I'm using Directory.Delete(strPath); for that. It throws an exception if folder is not empty. But I can't seem to figure out how to differentiate between that error and some other error (say, if the path was wrong, folder didn't exist, was inaccessible because of ACL, etc.)
I can do this with Win32 in a heartbeat, but I'm somewhat stumped in .NET.
Any ideas?
try
{
Directory.Delete(strPath);
}
catch (Exception ex)
{
//if(FolderWasNotEmpty){ all-good-not-an-error(); }
//else { show-error(); }
}
PS. I'm using .NET 3.5 for this project.

How can I retrieve the LoaderExceptions property from the Exception class? [duplicate]

I get a error message while updating my service reference:
Custom tool warning: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
How can I retrieve the LoaderException property?
Update: My errors went away when I reimported the domain object projects. I have no idea why this fixed the issue, but I'm happy it's working.
try
{
// load the assembly or type
}
catch (Exception ex)
{
if (ex is System.Reflection.ReflectionTypeLoadException)
{
var typeLoadException = ex as ReflectionTypeLoadException;
var loaderExceptions = typeLoadException.LoaderExceptions;
}
}
catch (ReflectionTypeLoadException ex)
{
foreach (var item in ex.LoaderExceptions)
{
MessageBox.Show(item.Message);
}
}
I'm sorry for resurrecting an old thread, but wanted to post a different solution to pull the loader exception (Using the actual ReflectionTypeLoadException) for anybody else to come across this.
Using Quick Watch in Visual Studio you can access the LoaderExceptions from ViewDetails of the thrown exception like this:
($exception).LoaderExceptions
Another Alternative for those who are probing around and/or in interactive mode:
$Error[0].Exception.LoaderExceptions
Note: [0] grabs the most recent Error from the stack

Unknown exception at declaration and initalisation of a Class

The main Problem is completely different, please skip to the Edit
I have an exception of an unknown type which doesn't even get thrown properly. Following Code provides the Context:
MMDataAccess.InitDemoDB();
MMDataAccess.InitInternalDB();
MMDataAccess.InitMaintDB();
try
{
SQLiteToDBLib sqltdbl = new SQLiteToDBLib();
sqltdbl.WriteToSQLite();
}
catch(Exception ex)
{
string message = ex.Message;
}
These are the very first lines of my first Activity in my app. The first 3 lines belong to my very own implementation of an in-memory database and are behaving nicely. The problem rises with the next two lines inside the try-block. The declaration and initalistation of the sqltdbl variable never happens. The constructor of SQLiteToDBLib looks like this:
public SQLiteToDBLib()
{
msc = new MSConnection();
}
The MSConnection class doesn't even have a constructor (except for the default one of course).
As you can see i've tried to catch any exceptions, but without success. everything i can figure out is, that a exception is thrown because of the debugger going into the catch section while ignoring everything that has to do with "ex". Without breakpoints everything seems fine. Just without the call to WriteToSQLite which should create a .sqlite file on the external Memory.
What can I do to resolve this error? Is there anything i can catch except the default Exception?
Edit:
After some testing with commented code something interresting happened. I could step into commented code. Well not exactly the commented code, but the code that was there before my changes. Visual Studio somehow shows me the things, that are changed in the file, but is compiling the old code. Up to now i tried to rebuild, clean and build the project in various combinations, unload and reload the project, Restart Visual Studio and restart Windows. Nothing has changed so far. I Will now proceed to create a new .cs File With the exact same Code. I'm working with VS 2013 Community
add static constructor to your SQLiteToDBLib class and perform all static objects initialization in it:
static SQLiteToDBLib()
{
// initialize static members here
}
If this doesn't give you a clue, try enabling CLRE exceptions-break in visual-studio:
DEBUG
Exceptions
Check the 'Common Language Runtime Exceptions' option (under the 'Thrown' column)
Press OK
Restart your app and try again

C# get the directory name from the DirectoryNotFoundException

I made an application that search for some files in some directories. When a directory isn't there it throws the DirectoryNotFoundException. I catch that exception but it doesn't have a DirectoryName property or something like that like the FileNotFoundException (FileName). How can I find the Directory Name from the exception properties?
There's no way to natively do this.
Add this class somewhere to your project:
public static class DirectoryNotFoundExceptionExtentions
{
public static string GetPath(this DirectoryNotFoundException dnfe)
{
System.Text.RegularExpressions.Regex pathMatcher = new System.Text.RegularExpressions.Regex(#"[^']+");
return pathMatcher.Matches(dnfe.Message)[1].Value;
}
}
Catch the exception and use the type extension like this:
catch (DirectoryNotFoundException dnfe)
{
Console.WriteLine(dnfe.GetPath());
}
It looks like a hack, but you can extract the path from the Message property. As for me, I would prefer to check if the directory exists first, by using the Directory.Exists method.
catch (DirectoryNotFoundException e)
{
// Result will be: Could not find a part of the path "C:\incorrect\path".
Console.WriteLine(e.Message);
// Result will be: C:\incorrect\path
Console.WriteLine(e.Message
.Replace("Could not find a part of the path \"", "")
.Replace("\".", ""));
}
It is a little inconsistent that FileNotFoundException has the file name, but DirectoryNotFoundException doesn't have the directory name, isn't it?
Here's a work around: Before you throw the exception, associate the errant directory name using Exception's Data property.
Immediately before you attempt to find files in a directory, save the name of the directory in a variable. Then begin a try block for the code that looks in that directory. You now have the directory name available should that block of code throw.
For example:
// ... somewhere in some method that's about to search a directory.
var dirName = directories[i]; // or something -- how do you get it before you pass it to DirectoryInfo?
try
{
SearchDirectory(dirName); // or a block of code that does the work
}
catch(Exception e)
{
// at this point, you know dirName. You can log it, add it to a list of erroring
// directories, or whatever. You could throw here, or swallow the error after logging it, etc.
}
Check that it exists first with Directory.Exists
If you are only looking to stomp this one bug in your IDE, then you can try doing this:
In Visual Studio, go to Debug -> Exceptions, then check the Thrown box for Common Language Runtime Exceptions. This will take you right to an exception when it happens, instead of waiting to get caught.
Sorry to dig up an old post, but as other has said it is pretty stupid that DirectoryNotFoundException does not have the directory as a property when FileNotFoundException does.
I've put it in as feature request for .NET:
http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/4472498-directorynotfoundexception-should-expose-the-name-
The format of the Message member of the DirectoryNotFoundException thrown from most Directory class methods is "Directory 'input' not found.". It shouldn't be hard to extract the input from this string.
Question thou, why would you need to get the input parameter from the exception if you're the one invoking the method with that exact parameter?

How to retrieve the LoaderException property?

I get a error message while updating my service reference:
Custom tool warning: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
How can I retrieve the LoaderException property?
Update: My errors went away when I reimported the domain object projects. I have no idea why this fixed the issue, but I'm happy it's working.
try
{
// load the assembly or type
}
catch (Exception ex)
{
if (ex is System.Reflection.ReflectionTypeLoadException)
{
var typeLoadException = ex as ReflectionTypeLoadException;
var loaderExceptions = typeLoadException.LoaderExceptions;
}
}
catch (ReflectionTypeLoadException ex)
{
foreach (var item in ex.LoaderExceptions)
{
MessageBox.Show(item.Message);
}
}
I'm sorry for resurrecting an old thread, but wanted to post a different solution to pull the loader exception (Using the actual ReflectionTypeLoadException) for anybody else to come across this.
Using Quick Watch in Visual Studio you can access the LoaderExceptions from ViewDetails of the thrown exception like this:
($exception).LoaderExceptions
Another Alternative for those who are probing around and/or in interactive mode:
$Error[0].Exception.LoaderExceptions
Note: [0] grabs the most recent Error from the stack

Categories