Created
January 25, 2018 06:09
-
-
Save mrgarita/0a24287ae5862944e587e9c8ec03792f to your computer and use it in GitHub Desktop.
C#:ダイアログでフォルダを選択する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Windows.Forms; | |
namespace SelectFolder | |
{ | |
public partial class Form1 : Form | |
{ | |
public Form1() | |
{ | |
InitializeComponent(); | |
} | |
/* | |
* 起動時の処理 | |
*/ | |
private void Form1_Load(object sender, EventArgs e) | |
{ | |
this.Text = ProductName; | |
button1.Text = "フォルダを選択する"; | |
} | |
/* | |
* フォルダダイアログを表示する | |
*/ | |
private void ShowFolderDialog() | |
{ | |
// FolderBrowserDialogクラスのインスタンス生成 | |
FolderBrowserDialog fbd = new FolderBrowserDialog(); | |
// ダイアログタイトルを設定 | |
fbd.Description = "フォルダを選択してください"; | |
// ルートフォルダの設定(RootFolderに何も指定しなければデスクトップがルートになる) | |
fbd.RootFolder = Environment.SpecialFolder.Desktop; | |
// 初期選択されているフォルダの設定(今回は、ローカルディスクのc:\を指定している) | |
// 初期選択フォルダは、RootFolder以下にあるフォルダである必要がある | |
fbd.SelectedPath = @"c:\"; | |
// ユーザーが新しいフォルダを作成できるようにする設定(デフォルトでtrue) | |
fbd.ShowNewFolderButton = true; | |
//ダイアログを表示する | |
if (fbd.ShowDialog() == DialogResult.OK) | |
{ | |
// 選択したフォルダ名を取得 | |
string myPath = fbd.SelectedPath; | |
//選択されたフォルダを表示する | |
MessageBox.Show(myPath + "が選択されました", "選択結果", MessageBoxButtons.OK, MessageBoxIcon.Information); | |
Console.WriteLine(myPath); | |
} | |
} | |
/* | |
* ボタンを押した時 | |
*/ | |
private void button1_Click(object sender, EventArgs e) | |
{ | |
ShowFolderDialog(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment