5

How do I extract just the file name excluding the namespace using the following code? Currently this code includes the entire namespace from GetManifestResourceNames().

 Assembly assembly = System.Reflection.Assembly.LoadFile(resourceLocation + @"\\" + file);


            string[] names = assembly.GetManifestResourceNames();

            foreach (var name in names.Where(x => x.EndsWith("xsd")).ToList())
            {
                using (System.IO.Stream stream = assembly.GetManifestResourceStream(name))
                {

                    using (System.IO.FileStream fileStream = new System.IO.FileStream(System.IO.Path.Combine(outputDir, name), System.IO.FileMode.Create))
Skyler Sanders
  • 175
  • 2
  • 13

1 Answers1

2

You can use GetManifestResourceInfo to get additional information, such as the file name.

Taking your example, you might end up with something like the following:

string[] names = assembly.GetManifestResourceNames();

foreach (var name in names.Where(x => x.EndsWith("xsd")).ToList())
{
    var info = assembly.GetManifestResourceInfo(name);
    if (info != null)
    {
        var fileName = info.FileName;
        // Do your stuff that needs filename here.
    }

}

EDIT: This SO post might be relevant, if you find GetManifestResourceInfo returning null in these cases: Why does GetManifestResourceStream returns null while the resource name exists when calling GetManifestResourceNames?

The resources should be set to build action of "Embedded Resource", and there is the code security gotcha that is mentioned here: http://adrianmejia.com/blog/2011/07/18/cs-getmanifestresourcestream-gotcha/

mars-red
  • 331
  • 2
  • 13
  • 1
    For some reason GetManifestResourceInfo always returns null. Or at least the FileName – Skyler Sanders Nov 02 '17 at 19:23
  • Hm, is the "Build Action" on the resources is set to "Embedded Resource"? – mars-red Nov 02 '17 at 19:27
  • Also, see this I think it's quite relevant: https://stackoverflow.com/questions/10726857/why-does-getmanifestresourcestream-returns-null-while-the-resource-name-exists-w – mars-red Nov 02 '17 at 19:29
  • Yeah the Build Action is set to Embedded resource because I can save the XSD with the full namespace & file name .xsd. – Skyler Sanders Nov 02 '17 at 19:31
  • Could it be the code security issue I linked to in my edited post? – mars-red Nov 02 '17 at 19:33
  • It could be. I tried setting the in the csproj file and it still doesn't work. – Skyler Sanders Nov 02 '17 at 19:43
  • Other than some hackey and brittle solution like regexing the full name, I think I'm out of helpful suggestions. Perhaps it would be worthwhile to spool this up as a separate SO question, about why GetManifestResourceInfo is returning null for you. If it's none of the reasons mentioned in the linked posts, then it probably warrants its own. – mars-red Nov 02 '17 at 19:45
  • Turns out it was a MSI configuration issue was the reason FileName was null. – Skyler Sanders Oct 09 '18 at 15:03