Read text file from C# Resources

2020-02-09 07:36发布

问题:

I need to read a file from my resources and add it to a list. my code:

private void Form1_Load(object sender, EventArgs e)
{
    using (StreamReader r = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("myProg.myText.txt")))
    {
        //The Only Options Here Are BaseStream & CurrentEncoding
    }
}

Ive searched for this and only have gotten answers like "Assembly.GetExecutingAssembly...." but my program doesnt have the option of Assembly.?

回答1:

Try something like this :

string resource_data = Properties.Resources.test;
List<string> words = resource_data.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries).ToList();

Where



回答2:

You need to include using System.Reflection; in your header in order to get access to Assembly. This is only for when you mark a file as "Embedded Resource" in VS.

var filename = "MyFile.txt"
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNameSpace." + filename));

As long as you include 'using System.Reflection;' you can access Assembly like this:

Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespace." + filename);

Or if you don't need to vary filename just use:

Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespace.MyFile.txt");

The full code should look like this:

using(var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("myProg.m‌​yText.txt"))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // Do some stuff here with your textfile
    }
}


回答3:

Just to follow on this, AppDeveloper solution is the way to go.

string resource_data = Properties.Resources.test;
string [] words = resource_data.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
foreach(string lines in words){
.....
}


回答4:

        [TestCategory("THISISATEST")] 
        public void TestResourcesReacheability() 
        { 
            byte[] x = NAMESPACE.Properties.Resources.ExcelTestFile; 
            string fileTempLocation = Path.GetTempPath() + "temp.xls"; 
            System.IO.File.WriteAllBytes(fileTempLocation, x);   

            File.Copy(fileTempLocation, "D:\\new.xls"); 
        }

You get the resouce file as a byte array, so you can use the WriteAllBytes to create a new file. If you don't know where can you write the file (cause of permissions and access) you can use the Path.GetTempPath() to use the PC temporary folder to write the new file and then you can copy or work from there.