elmattic
elmattic

Reputation: 12184

Unable to use Environment.GetResourceString static method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var x = Environment.GetResourceString("test"); //compile-time error
        }
    }
}

The error is: 'System.Environment' does not contain a definition for 'GetResourceString'.

EDIT: OP has stated that he's using the Compact Framework, v3.5.

I dont get the picture, what's wrong with my code? Thanks!

Upvotes: 5

Views: 6622

Answers (3)

ng256
ng256

Reputation: 87

You cannot access Environment.GetResourceString, but if you need access to mscorlib's internal error message, define your own implementation of that.

using System;
using System.Globalization;
using System.Reflection;
using System.Resources;

static class EnvironmentEx
{
    // Mscorlib's resources.
    private static ResourceSet resources = null;

    // Gets mscorlib's internal error message.
    public static string GetResourceString(string name)
    {
        if (resources == null)
        {
            var assembly = Assembly.GetAssembly(typeof(object));
            var assemblyName = assembly.GetName().Name;
            var manager = new ResourceManager(assemblyName, assembly);
            resources = manager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
        }
        return resources.GetString(name ?? throw new ArgumentNullException(nameof(name)));
    }

    // Gets parametrized mscorlib's internal error message.
    public static string GetResourceString(string name, params object[] args)
    {
        return string.Format(GetResourceString(name), args);
    }
    
    static void Main()
    {
        string message = GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", -1, 1);
        // message = "Argument must be between -1 and 1".
    }
}

P. S. Here a list of all messages with their ID.

Upvotes: 4

Simon
Simon

Reputation: 34880

Environment.GetResourceString is not public

internal static string GetResourceString(string key);

See Michael Petrottas answer for how to access resources or have a look at the samples here http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager.aspx

Upvotes: 8

Michael Petrotta
Michael Petrotta

Reputation: 60942

Environment.GetResourceString appears to be present, according to MSDN, only in version 2.0 of the Compact Framework. If the article is to be believed, it's never existed in the standard framework.

What are you trying to do? If it's localization you're after, you may want ResourceManager.GetString.

System.Resources.ResourceManager myManager = new 
   System.Resources.ResourceManager("ResourceNamespace.myResources", 
   myAssembly);

// Retrieves String and Image resources.
string myString = myManager.GetString("StringResource");

Upvotes: 6

Related Questions