使用 C# 获取解决方案文件的父文件夹的路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19001423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:51:34  来源:igfitidea点击:

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

c#filepathiostreamreader

提问by User1204501

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

我是 C# 的初学者,我有一个文件夹,我正在从中读取文件。

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.slnis in C:\X0\A\XXX\then read the .txtfiles in C:\X0\A\.

所以,如果我的文件XXX.slnC:\X0\A\XXX\,然后读取.txt的文件C:\X0\A\

采纳答案by Thilina H

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);

回答by Moo-Juice

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.

我觉得,如果您的应用程序根据文件路径和解决方案路径之间的关系依赖于文件的位置,那将是一种疏忽。虽然您的程序很可能在 处执行Solution/Project/Bin/$(ConfigurationName)/$(TargetFileName),但只有在您从 Visual Studio 的范围内执行时才有效。在 Visual Studio 之外,在其他情况下,情况不一定如此。

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 answeron parsing command line arguments.

  1. 将文件作为项目的一部分包含在内,并在其属性中将其复制到输出文件夹。然后,您可以访问该文件:

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

    请注意,在部署期间,您必须确保此文件也与可执行文件一起部署。

  2. 使用命令行参数指定启动时文件的绝对路径。这可以在 Visual Studio 中默认设置(请参阅项目属性 -> 调试选项卡 -> 命令行参数”。例如:

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

    有许多方法和库涉及解析命令行。这是有关解析命令行参数的堆栈溢出答案

回答by Anand

string path = Application.StartupPath;

回答by stevepkr84

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;

需要 using System.IO;

回答by Demetris Leptos

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

您可能会喜欢这种更通用的解决方案,它依赖于*.sln通过扫描当前或选定的所有父目录来查找解决方案文件,同时涵盖找不到解决方案目录的情况!

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 willreside 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.anchoror mySuperSpecificFileNameToRead.ext;P If you want me to write the method I can - just let me know.

现在,警告.. 您的应用程序应该是解决方案不可知的 - 除非这是我不介意的某个解决方案处理工具的个人项目。了解这一点,您的应用程序一旦分发给用户,驻留在没有解决方案的文件夹中。现在,您可以使用“锚”文件。例如,像我一样搜索父文件夹并检查是否存在空文件app.anchormySuperSpecificFileNameToRead.ext;P 如果您希望我编写我可以的方法 - 请告诉我。

Now, you may really enjoy! :D

现在,你可能真的很享受!:D

回答by yatagarasu

If for some reason you want to compile in solution path to your project, you can use T4 template to do this.

如果由于某种原因您想在项目的解决方案路径中进行编译,您可以使用 T4 模板来执行此操作。

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="EnvDTE" #>
<#@ import namespace="EnvDTE" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
<#@ parameter name="model" type="System.String" value=""#>
<#
    IServiceProvider serviceProvider = (IServiceProvider)this.Host;
    DTE dte = serviceProvider.GetService(typeof(DTE)) as DTE;
#>
using System;
using System.IO;

namespace SolutionInfo
{
    public static class Paths
    {
        static string solutionPath = @"<#= Path.GetDirectoryName(dte.Solution.FullName) #>";
    }
}

Tah will work from Visual Studio only I think.

只有我认为 Tah 可以在 Visual Studio 中工作。