Monday, March 7, 2011

how to get file from resources as a stream? (.net)

I've got few files in resources (xsd files) that i use for validating received xml messages. The resource file i use is named AppResources.resx and it contains a file called clientModels.xsd. When i try to use the file like this: AppResources.clientModels, i get a string with the file's content. i would like to get a stream instead. i do not wish to use assembly.GetManifestResourceStream as i had bad experiences with it (using these streams to archive files with SharpZipLib didn't work for some reason). is there any other way to do it? i've heard about ResourceManager - is it anything that could help me?

From stackoverflow
  • Could you feed the string you get into a System.IO.StringReader, perhaps? That may do what you want. You may also want to check out MemoryStream.

  • Hello

    I would normallly use the way you do not want to use.

    however here is a link to a smaple which uses the resourse manager. (I have not used this)

    Sample of resourse manager

    except use

    resourceManager.GetStream()

    HTH bones

    agnieszka : the link doesn't work
  • here is the code from the link

    //Namespace reference
    using System;
    using System.Resources;
    
    
    #region ReadResourceFile
    /// <summary>
    /// method for reading a value from a resource file
    /// (.resx file)
    /// </summary>
    /// <param name="file">file to read from</param>
    /// <param name="key">key to get the value for</param>
    /// <returns>a string value</returns>
    public string ReadResourceValue(string file, string key)
    {
        //value for our return value
        string resourceValue = string.Empty;
        try
        {
            // specify your resource file name 
            string resourceFile = file;
            // get the path of your file
            string filePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
            // create a resource manager for reading from
            //the resx file
            ResourceManager resourceManager = ResourceManager.CreateFileBasedResourceManager(resourceFile, filePath, null);
            // retrieve the value of the specified key
            resourceValue = resourceManager.GetString(key);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            resourceValue = string.Empty;
        }
        return resourceValue;
    }
    #endregion
    

    I did not write the code it came from

    http://www.dreamincode.net/code/snippet1683.htm

    HTH

    bones

  • I have a zip file loaded as a resource, and referencing it directly from the namespace gives me bytes, not a string. Right-click on your file in the resources designer, and change the filetype from text to binary. Then you will get a bytearray, which you could load into a MemoryStream.

0 comments:

Post a Comment