Get file from assembly

I want to read the file path from the following structure

The structure is similar: AssemblyName → MyFiles (Folder) → Text.txt

Here I want to get the path to Text.txt. Please, help

+4
source share
3 answers

I think you are looking for a file built into the assembly. Check out this question . The first answer explains how to set up the embedded file, as well as how to get it from the code.

+4
source

You can do

string assemblyPath = Assembly.GetExecutingAssembly().Location; string assemblyDirectory = Path.GetDirectoryName(assemblyPath); string textPath = Path.Combine(assemblyDirectory, "MyFiles", "Test.txt"); string text = File.ReadAllText(textPath); 

... just smash it ... but you could write it all on one line, not to mention the need ...

alternatively, if your Environment.CurrentDirectory is already installed in the directory of your build site for execution, you can simply do

 File.ReadAllText(Path.Combine("MyFiles", "Text.txt")); 
+4
source

Jeff told how you get the path, and your comment on his answer is the file you want to open, actually included in your project?

In the properties area for the corresponding file, see the Copy to Output Directory option - it defaults to Do not copy . You want to install it in Copy Always or Copy if Newer if you want to include the file in the output directory with your compiled program.

As a general note, you should always wrap any IO in the appropriate catch try block, or use the static File.Exists(path) method to check for a file

0
source

Source: https://habr.com/ru/post/1398858/


All Articles