简体   繁体   中英

Accessing file in Assembly

I am working in Visual Studio C# and would like to access one of the files in console application assembly. I don't want to use Application.ExecutePath as that will require my importing the Windows Forms library which I do not need. The Tablelist.txt file lies in my project file, and all I would like to do is read it's content directly.

StreamReader sr = new StreamReader(
    Assembly.GetExecutingAssembly().GetManifestResourceStream(
        Assembly.GetExecutingAssembly().GetName().Name + ".TableList.txt"));

How do I access the resource stream?

To directly read the contents of a file:

  1. Add a new 'Resources file' to your application and name it 'TextResources.resx'.
  2. Double click the newly created file. Click 'Add Resource', 'Add existing file', navigate to your file 'TableList.txt' and click the button 'Open'. The file will be added as a resource.

Now use the following snippet to read the contents of the file:

using System;
using System.Reflection;
using System.Resources;

// Gets a reference to the current assembly.
string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;            
// Creates the ResourceManager.
ResourceManager resourceManager = new ResourceManager(String.Format("{0}.TextResources", assemblyName), Assembly.GetExecutingAssembly());
// Retrieves resource and displays it.
string textFileContents = resourceManager.GetString("TableList");
Console.Write(textFileContents);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM