MyDocumentsフォルダなど、環境によって場所が異なる可能性のあるフォルダのパスを取得するには「Environment.GetFolderPath」を使用します。
string Environment.GetFolderPath(Environment.SpecialFolder folder)
For example
Console.WriteLine("MyPictures : {0}",Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));パスの操作
特定のパスから拡張子を取得するなどの操作を行うには『System.IO.Path』を使用します。static void Main(string[] args)
{
string fileName = "test.jpg";
string dir = "C:\\mydir";
string path = Path.Combine(dir, fileName);
Console.WriteLine(
//ファイル名を除いたパス(ディレクトリ)を返します。
"GetDirectoryName : {0}" +
//拡張子を返します。
"\nGetExtension : {1}" +
//ファイル名と拡張子を返します。
"\nGetFileName : {2}" +
//ファイル名のみを返します。
"\nGetFileNameWithoutExtension : {3}" +
//指定したパス文字列の絶対パスを返します。
"\nGetFullPath : {4}" +
//指定したパスのルート ディレクトリを返します。
"\nGetPathRoot : {5}" +
//ランダムなファイル名を返します。
"\nGetRandomFileName : {6}" +
//拡張子を変更します。
"\nChangeExtension : {7}" +
//ルートディレクトリを返します。
"\nIsPathRooted : {8}",
Path.GetDirectoryName(path),
Path.GetExtension(path),
Path.GetFileName(path),
Path.GetFileNameWithoutExtension(path),
Path.GetFullPath(fileName),
Path.GetPathRoot(path),
Path.GetRandomFileName(),
Path.ChangeExtension(path, "bmp"),
Path.IsPathRooted(path)
);
}カレントディレクトリとステムディレクトリを取得するメソッドの重複
カレントディレクトリ- Directory.GetCurrentDirectory()
- Environment.CurrentDirectory
システムディレクトリ
- Environment.GetFolderPath(Environment.SpecialFolder.System)
- Environment.SystemDirectory
もう少し現実的な例を2つほど…
MyPicturesフォルダ直下にあるフォルダ名を取得し表示します
foreach (string p in Directory.GetDirectories(
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)))
{
Console.WriteLine(p.Split('\\').Last());
}'\'で分けて最後の値を取得しています。MyPicturesフォルダ直下にあるファイル名を取得し表示します
foreach (string f in Directory.GetFiles(
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)))
{
Console.WriteLine(Path.GetFileName(f));
}「Path.GetFileName」を使用してファイル名を取得しています。





0 Comments:
コメントを投稿