How do I access embedded resources in Visual Studios using Visual C #?

I've seen many other posts about this and they don't make any sense. This is the structure I saw from another post.

var assembly = Assembly.GetExecutingAssembly();
var resourceName = "MyCompany.MyProduct.MyFile.txt";

using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
    string result = reader.ReadToEnd();
}

      

I don't understand what's going on in the part "MyCompany.MyProduct.MyFile.txt"

. Is it "WindowsFormApplication2.Properties.Resources.LabelData.txt"? Because it doesn't work. I keep getting NullReferenceException ... I am assuming it does not have the file I want. Here I have the code as it is.

public void readAllLabelValues()
        {

            var assembly = Assembly.GetExecutingAssembly();
            var resourceName = "WindowsFormsApplication2.WindowsFormsApplication2.LabelData.txt";

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))

            using (StreamReader Reader = new StreamReader(stream))
            {
                foreach (Label label in tableLayoutPanel1.Controls.OfType<Label>())
                {
                    label.Text = (Reader.ReadLine());
                }
            }
        }

      

Help is appreciated.

+3


source to share


3 answers


I figured out that you can use Application.StartUpPath for this. This is the code I used to create a valid path to it:

string fileLocation = Path.Combine(Application.StartupPath, "programData.txt");

            if (!File.Exists(fileLocation))
            {
                File.Create(fileLocation);
            }

      



Then, to read and write for it, just create a StreamReader or StreamWriter pointing to fileLocation.

0


source


you can see on the Microsoft site ( https://support.microsoft.com/en-us/kb/319292 ) that the naming convention is:

The compiler adds the project root namespace to the resource name when it is included in the project. For example, if the root namespace of your project is MyNamespace, the resources are named MyNamespace.MyTextFile.txt and MyNamespace.MyImage.bmp.

you can use a debugger to find out what the resource name is using the following code:



thisExe = System.Reflection.Assembly.GetExecutingAssembly();
string [] resources = thisExe.GetManifestResourceNames();

      

if you don't see it in resources, make sure in the properties of the text file you change the build action to be an embedded resource and not the default.

0


source


WindowsFormApplication2.LabelData.txt

      

0


source







All Articles