24

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.?

4

4 回答 4

40

Try something like this :

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

Where

enter image description here

于 2013-03-30T19:23:17.433 回答
11

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
    }
}
于 2013-03-30T19:23:32.777 回答
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){
.....
}
于 2013-09-10T13:16:09.860 回答
1
        [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.

于 2014-09-09T16:01:28.620 回答