Getting path to the parent folder of the solution file using C#

回眸只為那壹抹淺笑 提交于 2020-02-20 07:14:50

问题


I am a beginner in C#, and I have a folder from which I am reading a file.

I want to read a file which is located at the parent folder of the solution file. How do I do this?

string path = "";
StreamReader sr = new StreamReader(path);

So if my file XXX.sln is in C:\X0\A\XXX\ then read the .txt files in C:\X0\A\.


回答1:


Try this:

string startupPath = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName,"abc.txt");

// Read the file as one string. 
string text = System.IO.File.ReadAllText(startupPath);



回答2:


You may enjoy this more general solution which depends on finding the solution *.sln file by scanning all parent directories from current or selected one while covering the case of not finding the solution directory!

public static class VisualStudioProvider
{
    public static DirectoryInfo TryGetSolutionDirectoryInfo(string currentPath = null)
    {
        var directory = new DirectoryInfo(
            currentPath ?? Directory.GetCurrentDirectory());
        while (directory != null && !directory.GetFiles("*.sln").Any())
        {
            directory = directory.Parent;
        }
        return directory;
    }
}

Usage:

// get directory
var directory = VisualStudioProvider.TryGetSolutionDirectoryInfo();
// if directory found
if (directory != null)
{
    Console.WriteLine(directory.FullName);
}

In your case:

// resolve file path
var filePath = Path.Combine(
    VisualStudioProvider.TryGetSolutionDirectoryInfo()
    .Parent.FullName, 
    "filename.ext");
// usage file
StreamReader reader = new StreamReader(filePath);

Enjoy!

Now, a warning.. Your application should be solution-agnostic - unless this is a personal project for some solution processing tool I wouldn't mind. Understand that, your application once distributed to users will reside in a folder without the solution. Now, you can use an "anchor" file. E.g. search parent folders like I did and check for existence of an empty file app.anchor or mySuperSpecificFileNameToRead.ext ;P If you want me to write the method I can - just let me know.

Now, you may really enjoy! :D




回答3:


It would be remiss, I feel, if your application relied on the location of a file based on the relationship between the file path and the solution path. Whilst your program may well be executing at Solution/Project/Bin/$(ConfigurationName)/$(TargetFileName), that works only when you are executing from within the confines of Visual Studio. Outside of Visual Studio, in other scenarios, this is not necessarily the case.

I see two options:

  1. Include the file as part of your project, and in its' properties, have it copied to the output folder. You can then access the file thusly:

    string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Yourfile.txt");
    

    Note, during deployment you'll have to ensure that this file is also deployed alongside your executable.

  2. Use command line arguments to specify the absolute path to the file on startup. This can be defaulted within Visual Studio (see Project Properties -> Debug Tab -> Command line arguments". e.g:

    filePath="C:\myDevFolder\myFile.txt"
    

    There's a number of ways and libraries concerning parsing the command line. Here's a Stack Overflow answer on parsing command line arguments.




回答4:


I think this is what you want. Not sure if it's a good idea when publishing though:

string dir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.FullName;

Requires using System.IO;




回答5:


string path = Application.StartupPath;


来源:https://stackoverflow.com/questions/19001423/getting-path-to-the-parent-folder-of-the-solution-file-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!