Read text file from C# Resources

跟風遠走 提交于 2019-11-30 07:05:57

问题


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.



来源:https://stackoverflow.com/questions/15722455/read-text-file-from-c-sharp-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!