【WPF】関数まとめ

ユーザー名取得

string userName = Environment.UserName; //userNameにユーザー名を取得

メッセージボックスを表示

MessageBox.Show(userName);

//はい、いいえボタンをつける
var ret = MessageBox.Show(“MessageBox”,””, MessageBoxButton.YesNo);
if(ret == MessageBoxResult.Yes) //はいの時

ファイル・フォルダの存在を確認

if(System.IO.File.Exists(ファイルフルパス)==true) {} //ファイルの存在を確認
if(System.IO.Directory.Exists(フォルダフルパス)==true) {} //フォルダの存在を確認

フォルダ・ファイルを作成

//Cドライブ直下にtestフォルダを作成
Directory.CreateDirectory(@”C:\test”);

//testフォルダにtest.txtファイル作成
FileInfo fi = new FileInfo(@”C:\test\test.txt”);
FileStream fs = fi.Create();
fs.Close();

フォルダ・ファイルを削除

//ファイルの削除
System.IO.File.Delete(@”C:\test\test.txt”);

//フォルダの削除
System.IO.Directory.Delete(@”C:\test\sub1″,true);
//sub1フォルダを削除する。sub1フォルダ内にフォルダが入っているとエラーが返るので、trueを入れることで内部のサブフォルダもまとめて削除される

ファイル・フォルダを移動

System.IO.File.Move(@移動元,@移動先); //ファイルの移動
System.IO.Directory.Move(@移動元,@移動先); //フォルダの移動

指定したパスのフォルダ名・ファイル名を取得

string path = @”C:\test\test.txt”;
//フォルダ名取得
string folderName = System.IO.Path.GetDirectoryName(path); // C:\test
//ファイル名取得
string fileName = System.IO.Path.GetFileName(path); // test.txt

ファイルをコピー

System.IO.File.Copy(@”C:\test\text1.txt”, @”C:\test\text2.txt”);
//text1=コピー元、text2=コピー後ファイル

テキストファイルの編集

string note1;
StreamWriter sw = new StreamWriter(note1);
note1 = “test”;
sw.WriteLine(note1);
sw.Close;

テキスト改行

string note1;
note1 = Environment.NewLine;

アプリを終了する

this.Close();

コンボボックスの使い方

//リストへの追加
comboBox1.Item.Add(“Japan”); //コンボボックスの選択肢にJapanを追加

//呼び出し
comboBox1.Text;

配列・リスト・Dictionaryの宣言と初期化

配列
int[3] hairetsu; //宣言
int[] hairetsu = {1,2,3}; //初期化

リスト
List<int> list1 = new List<int>(); //宣言
List<int> list1 = new List<int>(){1,2,3}; //初期化

Dictionary
Dictionary<Key,Value> dictionary1 = new Dictionary<Key,Value>(); //宣言
Dictionary<Key,Value> dictionary1 = new Dictionary<Key,Value>(){Key1,Value1},{Key2,Value2}; //初期化

リストへの値の追加と削除

//文字列リストの宣言
List<string> list1 = new List<string>();

//文字列の追加
list1.Add(“AA”);

//削除
list1.Remove(“AA”);

//全削除
list1.Clear();

外部EXEを起動

var proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = @”起動したいアプリのフルパス”;
proc.Start(); //起動

//起動したアプリの終了を待つとき
proc.WaitForExit(); //アプリが終了したとき、以降の処理が実行される

文字列をキーワードで分割して別配列に格納する

string splitBefore = “AA,BB”;
string[] splitAfter = splitBefore.Split(“,”); //[0]=AA, [1]=BB

文字列を後ろから削除する

string before = “abcde”;
string after = before.Remove(before.Length-2); //後ろから2文字削除

文字列の指定位置の文字を削除する

文字列.Remove(削除開始位置, 削除する文字数)
文字列.Remove(削除開始位置) //指定位置までは残る

string before = “abcde”;
string after = before.Remove(2,4); //after = “ae”
string after = before.Remove(3); //after = “abc”

文字列に指定文字が存在するか調べる

If(textbox1.Text.Contains(“abc”) == true){ } //abcが含まれる時、trueを返す

文字列が指定文字で終わっているか調べる

String fileName = textbook.Text;
if(fileName.EndsWith(“.bat”)) { } //.batで終わっている時、trueを返す

コメント

タイトルとURLをコピーしました