Failing to Run in Partial Trust Gracefully

When you write an application that requires a high level of trust to run properly, when a user tries to run that application from a location that gives it lower levels of trust, they're greeted with a rather unfriendly unhandled SecurityException.  This most commonly happens when your application requires FullTrust, and someone tries to run it from a network share.

While there's not much you can do about the dialog that's displayed when your main assembly has a declarative RequestMinimum for FullTrust, if the failure is occurring because of a failed stackwalk, its pretty easy to fail more gracefully.

Obviously, you could catch each SecurityException, and even attempt to recover from it, but for a lot of applications, it's much easier to put a snippet of code like the following in Main, in order to check the application's trust level before it begins any work.  Then if you establish that the level of trust isn't high enough, you can fail gracefully, leaving the user with some information about what needs to be corrected.

public static int Main()
{
    if(!IsFullTrust)
    {
        Console.WriteLine("This application requires FullTrust to run. Try copying it to your local computer, and running it again.");
        return ErrorCode;
    }

    ....
}

/// <summary>
/// Check to see if the calling code is executing with FullTrust
/// </summary>
private static bool IsFullTrust
{

    [MethodImpl(MethodImplOptions.NoInlining)]
    get
    {
        try
        {
            new PermissionSet(PermissionState.Unrestricted).Demand();
        }
        catch(SecurityException)
        {
            return false;
        }

        return true;
    }
}