サンプル集  >  C#  >  絶対パスか相対パスか調べる
絶対パスか相対パスか調べる
2017/11/20

指定されたパスが絶対パスか相対パスか調べます。

◆環境
OS Windows 7 Professional Service Pack 1 (64bit)
C# 01018-587-4054026-70893

以下の手順を行います。

  1. [ファイル]-[新規作成]-[プロジェクト]を選択します。
  2. 「プロジェクトの種類」欄で[Visual C#]を選択し、[コンソール アプリケーション]を選択します。
    「プロジェクト名」は「PathTest」にします。

パスを調べるのにSystem.IO.Path.IsPathRooted()を使います。

Program.cs
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace PathTest
{
    class Program
    {
        static void Main( string[] args )
        {
            PathCheck( "..\\Debug" );
            PathCheck( "C:\\Temp" );

            // 存在しないパス
            PathCheck("C:\\AAA");

            Console.Read();
        }

        static bool PathCheck( string path )
        {
            bool ret = Path.IsPathRooted( path );

            if ( ret )
            {
                Console.WriteLine( "絶対パス:{0}", path );
            }
            else
            {
                Console.WriteLine( "相対パス:{0}", path );
            }

            return ret;
        }
    }
}

実行してみます。

相対パス:..\Debug
絶対パス:C:\Temp
絶対パス:C:\AAA

実際には存在しないパスを指定しても、絶対パスか相対パスかの判定がされました。 単純に文字列だけで判断しているようです。

▲ PageTop  ■ Home


Copyright (C) 2017 ymlib.com