Resource files not found from .resx file

119 views Asked by At

I have added some existing configuration files in a Resource file (.resx). I have written the following code to get the files from resource file and write those files in a destination folder configured in Settings.settings file.

using (var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Fs.ExtendedImporter.Application.Configuration.SampleConfigFiles.ExampleFiles.resx"))
{
    if (resourceStream != null)
    {
        using (var resourceReader = new ResourceReader(resourceStream))
        {
            foreach (DictionaryEntry resource in resourceReader)
            {
                string resourceName = (string)resource.Key;
                byte[] resourceData = (byte[])resource.Value;
                string destinationFile = Path.Combine(Settings.Default.ApplicationConfiguration, resourceName);

                if (!File.Exists(destinationFile))
                {
                    File.WriteAllBytes(destinationFile, resourceData);
                }
            }
        }
    }
    else
    {
        Logger.Log.Error("Resource file not found.");
    }
}

But resourceSteam variable is returning null in this code.

I have checked the resource(.resx) file property and got ensured that the Build action is set to Embedded Resource.

enter image description here

dotpeek screenshot-

enter image description here

Also the namespace is correct in GetManifestResourceStream() method.

What could be the problem? I appreciate your valuable help.

1

There are 1 answers

0
Nafisian Castle On

Finally, I found ResourceManager as alternative and it worked for me-

// Create a ResourceManager for the resource file
var resourceManager = new ResourceManager(
    "Fs.ExtendedImporter.Application.Configuration.SampleConfigFiles.ExampleFiles",
    Assembly.GetExecutingAssembly());

// Get all resource names in the resource file
var resourceSet = resourceManager.GetResourceSet(System.Globalization.CultureInfo.CurrentCulture, true, true);

foreach (var resource in resourceSet)
{
    var resourceEntry = (System.Collections.DictionaryEntry)resource;
    string resourceName = resourceEntry.Key.ToString();
    object resourceValue = resourceEntry.Value;
    string destinationFile = Path.Combine(Settings.Default.ApplicationConfiguration, resourceName + ".xml");
    // Handle string resources
    if (resourceValue is string stringValue)
    {
        if (!File.Exists(destinationFile))
        {
            File.WriteAllText(destinationFile, stringValue);
        }
    }
    // Handle binary resources (byte arrays)
    else if (resourceValue is byte[] binaryValue)
    {
        if (!File.Exists(destinationFile))
        {
            File.WriteAllBytes(destinationFile, binaryValue);
        }
    }
}