【C#】パス(Path)の扱いについて

ディレクトリとファイル名の結合

 * System.IO.Path.Combine() を使用する

サンプル

string filePath = @"C:\TK\";

// ファイル名の作成 
string fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + "TEST" + ".txt";

// ファイルパス結合
fileName = System.IO.Path.Combine(filePath, fileName);

注意

 * System.IO.Path.Combine() は、あくまで、ディレクトリと「ファイル名」の結合である。
   以下の例のように、「ディレクトリ付ファイル名」は、第2引数が返却される

string FILENAME_FOR_EXPLANATION = @"\test\test.txt"; // ディレクトリ付ファイル名

string filename = System.IO.Path.Combine(
    Application.ExecutablePath, this.FILENAME_FOR_EXPLANATION);

System.out.println("filename is {0}.", filename); // 出力:「filename is \\test\\test.txt」
From Framework4
 * Framework4から文字列の配列も対応するようになった

string[] paths = { @"C:\aaaa", "bbb", "cc", "d" };
string fullPath = System.IO.Path.Combine(paths);
this.label1.Text = fullPath; // 「C:\aaaa\bbb\cc\d」が出力

ディレクトリ名のみ取得(ファイル名省く)

 * System.IO.Path.GetDirectoryName() を使用する

■ ファイル名のみ取得

 * Path.GetFileName() を使用する

サンプル

// ファイルのパス文字列(フルパス)からファイル名の部分を取り出す
string textTxt = Path.GetFileName(@"c:\test\text.txt"); // textTxt = "text.txt";

参考資料

http://www.atmarkit.co.jp/fdotnet/dotnettips/164getfilename/getfilename.html

■ 「絶対パス」か「相対パス」かを判断する

 * System.IO.Path.IsPathRooted() を使用する

サンプル

//string filePath = @"C:\test\test.txt";
string filePath = @".\test.txt";

if(System.IO.Path.IsPathRooted(filePath))
{
    MessageBox.Show("絶対パス : " + filePath);    
}
else
{
    MessageBox.Show("相対パス : " + filePath);    
}