user1238374
user1238374

Reputation: 83

Get File From an Assembly

I want to read a file path from the following structure

The Structure is like : AssemblyName -> MyFiles (Folder) -> Text.txt

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

Upvotes: 7

Views: 13206

Answers (3)

Eric Andres
Eric Andres

Reputation: 3417

I think what you're looking for is a file embedded in the assembly. Check out this question. The first answer explains how to set up an embedded file, as well as how to get it from code.

Upvotes: 7

RobV
RobV

Reputation: 28636

Jeff has covered how you get the path, wrt your comment on his answer is the file you want to open actually included in your project output?

Under the properties pane for the relevant file look at the Copy to Output Directory option - it generally defaults to Do not copy. You will want to set it to Copy Always or Copy if Newer if you want to include a file in the output directory with your compiled program.

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

Upvotes: 1

Jeff
Jeff

Reputation: 36553

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 to split it up some...but you could write it all in one line needless to say...

alternatively, if your Environment.CurrentDirectory is already set to the directory of your executing assembly's location, you could just do

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

Upvotes: 7

Related Questions