简体   繁体   English

在程序集中访问文件

[英]Accessing file in Assembly

I am working in Visual Studio C# and would like to access one of the files in console application assembly. 我正在Visual Studio C#中工作,并且想访问控制台应用程序程序集中的文件之一。 I don't want to use Application.ExecutePath as that will require my importing the Windows Forms library which I do not need. 我不想使用Application.ExecutePath因为这将需要导入不需要的Windows Forms库。 The Tablelist.txt file lies in my project file, and all I would like to do is read it's content directly. Tablelist.txt文件位于我的项目文件中,我要做的就是直接读取其内容。

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'. 将新的“资源文件”添加到您的应用程序,并将其命名为“ 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'. 单击“添加资源”,“添加现有文件”,导航到文件“ TableList.txt”,然后单击“打开”按钮。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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