Gregory Nozik Gregory Nozik - 2 months ago 7
ASP.NET (C#) Question

Embedding text file in asp.net project

I added text file to my web project. Right click and clicking on properties
menu I choose ,Build Action -> Resource.

How can I retrieve the content of the file in my code behind page.

I try this but I received stream null

internal string GetFromResources(string resourceName)
{
Assembly assem = this.GetType().Assembly;
using (Stream stream = assem.GetManifestResourceStream(resourceName))
{
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}


But it's not working.

Please help

Answer

I solved it, below are the steps that I took.

First of all I defined text file as embedded resource. Second problem was that I did not added assembly name space to the text file.

So I changed the function and added namespace

internal string GetFromResources(string resourceName)
{

    Assembly assem = this.GetType().Assembly;
    **List<string> listNameSpaces = assem.GetTypes().Select(t => t.Namespace).Distinct().ToList<string>();**

    foreach (string ns in listNameSpaces)
    {
        **string nsResourceName = ns + "." + resourceName;**
        using (Stream stream = assem.GetManifestResourceStream(nsResourceName))
        {
            if (stream != null)
            {
                using (var reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }

    return string.Empty;
}