Help us understand the problem. What is going on with this article?

指定した名前のフォルダまでのパスを抽出する

More than 5 years have passed since last update.

よく使うのに忘れてしまうのでメモしときます。

var fullPath = @"C:\Users\user\Dir\Folder\hoge.txt";
var extractingDirName = "Dir";
var extractingStr = Path.DirectorySeparatorChar + extractingDirName + Path.DirectorySeparatorChar;
var idx = fullPath.LastIndexOf(extractingStr);
var extractedPath = fullPath.Substring(0, idx + extractingStr.Length);
Console.WriteLine(extractedPath); // => "C:\Users\user\Dir\"

*@kuchikios さんが指摘くださった問題に対応しました。

--
2015/12/15 追記
プロジェクトフォルダの取得に用いるのが便利だと思います.
(ソリューション名やパスの他の箇所などと重なる場合はこちらの方法が確実です.設定が面倒なのが難点ですが)

public static string GetProjectDirPath()
{
    var execPath = Environment.CurrentDirectory; // 実行ファイルのパス 
    var extractingDirName = "YourProjectName"; // プロジェクト名
    var extractingStr = Path.DirectorySeparatorChar + extractingDirName + Path.DirectorySeparatorChar;
    var idx = execPath.LastIndexOf(extractingStr);
    var projectPath = execPath.Substring(0, idx + extractingStr.Length);
    //Console.WriteLine(projectPath); // => "C:\Users\user\Desktop\SolutionName\YourProjectName\"
    return projectPath;
}
Go-zen-chu
Artificial Intelligence/Data Mining/Machine Learning/Statistic/Golang,C++,C#,Python,JS/ へっぽこプログラマ
https://amasuda.xyz
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away