Jay
Jay

Reputation:

C# opening file in a solution

I think this question might be trivial for the most of you but somehow I cannot find the answer... so, I have a Visual Studio 2008 Solution foo and a Project bar in this solution. In my bar-Project i've got a Directory called baz, it looks like this:

foo dir
 |
 +-> bar dir
      |
      +-> baz dir
           |
           +-> asd file

now I want to open my "asd file" in bar-project but need the exact path to "asd file", how can I find it? I tried simply "baz\asd" but it doesn't work.

Thanks!

J

Upvotes: 6

Views: 6590

Answers (4)

Arun
Arun

Reputation: 2523

It might be better to add a simple Target into the Build file (Project file - csproj for C#). Open csproj file in text mode and add:


<Target Name="AfterBuild"> <Copy SourceFiles="<SourceFileLocationRelativeToPrjFile>\<SourceFilename>" DestinationFiles="<SourceFilename>" />
</Target>

MS Build will take care of copying your file to the right place - that is right folder no matter what your Configuration (Debug/Release) is.

If you are interested in Publishing as well, you will need to go an extra mile, but I guess, you are not asking for that now - so, will keep it simple.

Upvotes: 0

Franci Penov
Franci Penov

Reputation: 76001

The relative location of the file is to the solution dir. So, to open it in the VS IDE, you can type in the Command window or the Find textbox on the Standard toolbar (Ctrl-D):

>open bar\baz\asd

If you want to do it at runtime, you need to distribute the source files with your application, as nothing guarantees it'll be executing anywhere near the solution tree.

If you want to do it from a VS Add-In, I am sure there's a class representing the solution, which you can use to enumerate the projects within it and then enumerate the file entries in the bar project.

Upvotes: 2

user7116
user7116

Reputation: 64068

You want to open the file in bar-project at runtime in a C# application? There are a few ways to accomplish this, and I'll give you the easiest.

  1. Go to the Properties for asd in Solution Explorer
  2. Set Build Action to Content
  3. Set Copy to Output Directory as Copy always (or Copy if newer)

You can then reference the file as follows in your C# (assuming your program does not change the current working directory away from the Executable Directory):

using (StreamReader reader = new StreamReader(@"baz\asd"))
{
    // ...
}

The other ways involve using embedded resources, which is not the most succinct of solutions.

Upvotes: 10

Eric J.
Eric J.

Reputation: 150108

If you mean open at runtime, the program actually runs in bar\bin\debug (or bar\bin\release), so you need to account for that.

Typically I'll do something like:

#if DEBUG
filename = @"..\..\baz\asd";
#else
filename = @"baz\asd";
#endif

Upvotes: 3

Related Questions