如何在 C# 中获取上面目录中的文件地址?

How can I get a file address in a directory above in C#?

我想从当前目录的文件中获取一个地址,例如: 我位于 MiProyecto/Socket/bin/Debug,我想从在 Socket/bin/Debug.

上运行的应用程序转到 MiProyecto\Ranking\Ranking.xml

我一直在寻找一种通用的方法,但我还没有找到具体的解决方案。我不想使用 OpenFileDialog.

我唯一知道的是获取 运行 应用程序的当前目录是 string path = Application.StartupPath; 但我不知道如何从该路径爬升到 Ranking\Ranking.xml

我也试过了:

string fullPath = Path.Combine(Application.StartupPath, @"..\"); Console.WriteLine("\n\n"+fullPath);

屏幕输出:

fullPath 写入控制台后,您没有对它进行任何操作。您需要将 fullPath 附加到您的 SerializadorRanking 调用中——即 SerializadorRanking(fullPath + "Ranking.xml");

string fullPath = Path.Combine(Application.StartupPath, @"..\"); 
Console.WriteLine("\n\n"+fullPath);
serializadorRanking = new SerializadorRanking(fullPath + @"Ranking\Ranking.xml");

相反,您可以通过 Path.Combine 函数附加整个字符串。

string fullPath = Path.Combine(Application.StartupPath, @"..\Ranking\Ranking.xml");
serializadorRanking = new SerializadorRanking(fullPath);

获取 MiProyecto 文件夹路径的通用方法,然后将其与 /Ranking/Ranking.xml[ 合并=12=]

using System;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string startupPath = Application.StartupPath;
            Console.WriteLine(startupPath); // .../MiProyecto/Socket/bin/Debug

            string folderName = "MiProyecto";
            DirectoryInfo di = new DirectoryInfo(startupPath);

            // Loop until found MiProyecto folder
            while (true)
            {
                if (di.Parent.FullName.EndsWith(folderName))
                {
                    break;
                }
                else
                {
                    di = new DirectoryInfo(di.Parent.FullName);
                }
            }

            Console.WriteLine(di.Parent.FullName); // .../MiProyecto
        }
    }
}

通过这种方式,您将始终获得MiProyecto文件夹的路径

MiProyecto/A/B/C/D/E/Debug 
MiProyecto/Ranking/Ranking.xml