简体   繁体   中英

open file from folder in visual studio 2012

I had a folder on my desktop with files in it. I copied that into the folder of my solution and in the solution explorer I referenced that folder into the solution. However, Im not able to open files in that folder with a relative path.

The relative path from the cs-file would be "../FolderIAdded/blabla" as seen in the solution explorer. But in the windows explorer, the path is differen of course:

Solutionfolder
- SolutionFolder.sln
- Solutionfolder.v11.suo
- SolutionFolder
-- bin
-- obj
-- Properties
-- TheFolderIAdded
-- App.config
-- Form1.cs
-- etc.

Here, it would be "FolderIAdded/blabla"

Where do I have to put that folder?

My goal: I want to be able to open files from that folder in my c#-code with a relative path.

You're assuming that your program runs in the directory where your source code is located. That's not the case. Depending on your configuration, your program will execute from a directory inside Solutionfolder\\bin.

One possible solution is to copy the file(s) to the output directory when you build your project.

文件属性

Another alternative is to embed the files into your application's assembly at compile time, although this precludes editing of them after deployment. To do that, set Build Action to 'Embedded Resource', then you can access them using the GetManifestResourceStream method of the Assembly class. The filename you need to give it will be derived from the path within the project structure, so in your example it would be "TheFolderIAdded.Filename.ext".

Yes, that's a dot, not a backslash.

Assuming the files are embedded in the same assembly the code that wants to read them is in, the code will look something like

var assembly = Assembly.GetExecutingAssembly();
using (var stream =
    assembly.GetManifestResourceStream("TheFolderIAdded.Filename.ext"))
using (var reader = new StreamReader(stream)) {
  string fileContents = reader.ReadToEnd();
}

I don't think it's a good idea to write relative path from .cs file. Better build the path base on where the application is executed : One example, there are plenty other on the web: How can I get the application's path in a .NET console application?

(Your application is not running in the solution's root folder but where the .exe file is locatated. For example when you debug a desktop application, it runs typically from [solution folder]/bin/debug/ )

Then make sure the file you want to open property Copy to Output Directory is set to Copy Always or Copy if newer . (Right click on the file in your Solution Explorer and click on "Properties" to be sure to access it.)

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