1 つのオプションは、System.IO.Directory.GetParent() を数回実行することです。実行中のアセンブリが存在する場所からいくつかのフォルダーを移動するより適切な方法はありますか?
私がやろうとしているのは、アプリケーション フォルダーの 1 つ上のフォルダーにあるテキスト ファイルを見つけることです。ただし、アセンブリ自体は bin 内にあり、アプリケーション フォルダーのいくつかの深さのフォルダーにあります。
1 つのオプションは、System.IO.Directory.GetParent() を数回実行することです。実行中のアセンブリが存在する場所からいくつかのフォルダーを移動するより適切な方法はありますか?
私がやろうとしているのは、アプリケーション フォルダーの 1 つ上のフォルダーにあるテキスト ファイルを見つけることです。ただし、アセンブリ自体は bin 内にあり、アプリケーション フォルダーのいくつかの深さのフォルダーにあります。
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\ としてパスを取得します
これは私にとって最もうまくいったものです:
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../"));
「正しい」パスを取得することは問題ではありませんでした。「../」を追加することは明らかにそれを行いますが、その後、指定された文字列は使用できません。最後に「../」を追加するだけだからです。で囲むとPath.GetFullPath()
絶対パスになり、使いやすくなります。
public static string AppRootDirectory()
{
string _BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
return Path.GetFullPath(Path.Combine(_BaseDirectory, @"..\..\"));
}
レベルの数を宣言して関数に入れたい場合は、関数を使用できますか?
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);
静的メソッド内の 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;
}
}
これは役立つかもしれません
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../../")) + "Orders.xml";
if (File.Exists(parentOfStartupPath))
{
// file found
}
移動先のフォルダーがわかっている場合は、そのインデックスを見つけてから部分文字列を見つけます。
var ind = Directory.GetCurrentDirectory().ToString().IndexOf("Folderame");
string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);