140

1 つのオプションは、System.IO.Directory.GetParent() を数回実行することです。実行中のアセンブリが存在する場所からいくつかのフォルダーを移動するより適切な方法はありますか?

私がやろうとしているのは、アプリケーション フォルダーの 1 つ上のフォルダーにあるテキスト ファイルを見つけることです。ただし、アセンブリ自体は bin 内にあり、アプリケーション フォルダーのいくつかの深さのフォルダーにあります。

4

12 に答える 12

43

c:\folder1\folder2\folder3\bin がパスの場合、次のコードは bin フォルダーのパス ベース フォルダーを返します。

//string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString());

string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString();

すなわち、c:\folder1\folder2\folder3

folder2 パスが必要な場合は、次の方法でディレクトリを取得できます

string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();

次に、 c:\folder1\folder2\ としてパスを取得します

于 2016-09-30T08:45:59.337 に答える
13

を使用..\pathして、パスから 1 レベル上に..\..\path移動したり、2 レベル上に移動したりできます。

Pathクラスも使えます。

C# パス クラス

于 2013-02-15T16:52:29.427 に答える
9

これは私にとって最もうまくいったものです:

string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../"));

「正しい」パスを取得することは問題ではありませんでした。「../」を追加することは明らかにそれを行いますが、その後、指定された文字列は使用できません。最後に「../」を追加するだけだからです。で囲むとPath.GetFullPath()絶対パスになり、使いやすくなります。

于 2014-05-21T09:54:28.253 に答える
6
public static string AppRootDirectory()
        {
            string _BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            return Path.GetFullPath(Path.Combine(_BaseDirectory, @"..\..\"));
        }
于 2020-11-07T07:46:52.050 に答える
5

レベルの数を宣言して関数に入れたい場合は、関数を使用できますか?

private String GetParents(Int32 noOfLevels, String currentpath)
{
     String path = "";
     for(int i=0; i< noOfLevels; i++)
     {
         path += @"..\";
     }
     path += currentpath;
     return path;
}

そして、次のように呼び出すことができます。

String path = this.GetParents(4, currentpath);
于 2013-02-15T16:56:44.157 に答える
2

静的メソッド内の Directory.GetParent(path) へのループ呼び出しを非表示にする方法です。

".." と Path.Combine をいじると、最終的にオペレーティング システムに関連するバグが発生するか、相対パスと絶対パスが混同されて単に失敗します。

public static class PathUtils
{
    public static string MoveUp(string path, int noOfLevels)
    {
        string parentPath = path.TrimEnd(new[] { '/', '\\' });
        for (int i=0; i< noOfLevels; i++)
        {
            parentPath = Directory.GetParent(parentPath ).ToString();
        }
        return parentPath;
    }
}
于 2021-08-23T17:34:45.983 に答える
1

これは役立つかもしれません

string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../../")) + "Orders.xml";
if (File.Exists(parentOfStartupPath))
{
    // file found
}
于 2015-07-20T12:35:23.490 に答える
1

移動先のフォルダーがわかっている場合は、そのインデックスを見つけてから部分文字列を見つけます。

            var ind = Directory.GetCurrentDirectory().ToString().IndexOf("Folderame");

            string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);
于 2018-05-06T19:07:56.127 に答える