C# .NET - サンプル

更新:

C# のサンプル。
自分がよく使うもののまとめ。

Visual C# の設定

Visual C# 2008 Express Edition 登録キー

  • Windows Live ID を取得する。
  • 14 桁の登録キーを取得する。
  • Visual C# 2008 Express Edition メニューの「ヘルプ」→ 「製品の登録」を選択。
  • 登録キーを「製品の登録」ダイアログボックスに貼り付け、「登録を完了する」ボタンをクリック。

Visual C# 2008 Express Editionでreleaseを表示する

  • メニューから「ツール」→「オプション」で「すべての設定を表示」をチェックした後、「プロジェクトおよびソリューション」→「ビルド構成の詳細を表示」をチェック。

アプリケーションのアイコンを変更する

  1. ソリューションエクスプローラーのPropertiesをダブルクリックし、設定画面を表示する。
  2. 「アプリケーション」にある「アイコン」を自作したアイコンに変更する。

アプリケーションのバージョン情報、著作権、製品名など

  • exeファイルを右クリックしたときに表示されるバージョン情報を変更するには、AssemblyInfo.cs の情報を編集する。

コンポーネントの追加

  • ソリューションエクスプローラーにある「参照設定」を右クリックし、「参照の追加」で必要なものを取り込む。
  • System.Web.dll などがある。
    //例
    using System.Text;
    using System.Web;
    
    string str = "テスト";
    Encoding encoding = Encoding.GetEncoding("shift_jis");
    str = HttpUtility.UrlEncode(str, encoding);
    


型、コードなど

文字コード、文字セット(charset)

文字コードは、規定の表記名か番号で指定する。
参考(MSDN)
コード 番号 ソース内表記名
SJIS 932 shift_jis
EUC-JP 51932 euc-jp
JIS 50220 iso-2022-jp
Unicode(UTF-8) 65001 utf-8
Unicode(UTF-16) 1200 utf-16
Unicode(UTF-16 Big Endian) 1201 unicodefffe
Unicode(UTF-7) 65000 utf-7
西ヨーロッパ言語(Windows, ANSI-Latin I) 1252 windows-1252
西ヨーロッパ言語(ISO, Latin I) 28591 iso-8859-1
西ヨーロッパ言語(Latin 9) 28605 iso-8859-15

範囲
string 文字列
int -(2^32)/2~(2^32 - 1)/2
uint 0~(2^32 - 1)
long -(2^64)/2~(2^64 - 1)/2
ulong 0~(2^64 - 1)
char 0~(2^16 - 1)
byte 0~(2^8 - 1)
sbyte -(2^8)/2~(2^8 - 1)/2
short -(2^16)/2~(2^16 - 1)/2
ushort 0~(2^16 - 1)
float 浮動小数点有効桁数7桁
double 浮動小数点有効桁数15~16桁
decimal 小数点有効桁数28~29桁

型変換(キャスト)

型の変換(キャスト)
int i = int.Parse("100");//文字列を数値に
string s = i.ToString();//数値を文字列に


制御文など

制御文など

  • if
    if(a == 0)
    {
    	b = 0;
    }
    else if(a == 1)
    {
    	b = 1;
    }
    else
    {
    	b = 2;
    }
    
    string str = "test";
    if(str.Equals("test"))
    {
    }
    
  • switch
    各caseは個々にbreakし、次のcaseに移ることはできない。
    switch(this.comboBox1.SelectedIndex)
    {
    	case 0:
    		a = 0;
    		break;
    	case 1:
    		a = 1;
    		break;
    	default:
    		a = 2;
    		break;
    }
    
  • for
    breakやcontinueは、whileやforeachなどの繰り返し処理でも使える。
    for(int i=0; i<10; i++)
    {
    	break;//繰り返しの処理から抜ける
    	
    	continue;//繰り返しの最初に戻る
    }
    
  • while
    int i = 0;
    while(i<10)
    {
    	i++;
    }
    
  • foreach
    testHash["a"] = "test a";
    testHash["b"] = "test b";
    foreach(string str in testHash.Keys)
    {
    }
    
  • try、catch、finally
    try
    {
    }
    catch(Exception ex)
    {
    }
    finally
    {
    }
    

パス、ファイル、ディレクトリ

アプリケーションのパス

アプリケーションの実行ファイルがあるフォルダのパス。
using System.IO;

string appliPath1 = Application.ExecutablePath;
string appliPath2 = Application.StartupPath;

カレントディレクトリのパス

アプリケーションが使用している現在のパス。
using System.IO;

//例1
string dirName2 = Directory.GetCurrentDirectory();

//例2
string dirName1 = Environment.CurrentDirectory;

パスからファイル名、フォルダ名などを取得

パスからファイル名などを取得する。
using System.IO;

//例1
string filepath = "C:\test\abc.txt";
string fileName1 = Path.GetFileName(filepath);//ファイル名(拡張子あり)
string fileName2 = Path.GetFileNameWithoutExtension(filepath);//ファイル名(拡張子なし)
string fileDir = Path.GetDirectoryName(filepath);//フォルダまでのパス
string fileExt = Path.GetExtension(filepath);//拡張子だけ(.を含む)

//例2
FileInfo fi = new FileInfo(opendlg.FileName);
string dirName = fi.DirectoryName;


==================== 文字列 ====================
■文字列を連結
	string str = str1 + str2;
	string str += str1;

■文字列を分割・切り取り
	Substring(分割開始位置, 取り出す長さ);
		string str = "test";
		string str1 = str.Substring(2);
		string str2 = str.Substring(2, 1);
	Split('char型');
		シングルクウォートで囲む
		string str = "test@sample.com";
		int a = str.Split('@');

■文字列の出現位置、文字一致
	IndexOf(検索対象文字, 検索開始位置);
		string str = "test@sample.com";
		int a = str.IndexOf("@");
		int b = str.IndexOf("e", 5);
	LastIndexOf(検索対象文字, 検索開始位置);
		string str = "test@sample.com";
		int a = str.LastIndexOf("@");
		int b = str.LastIndexOf("e", 5);
	StartsWith(検索対象文字)
		検索対象文字で始まるかどうか
		string str = "test@sample.com";
		if(str.StartsWith("test@"))
		{
		}
	EndsWith(検索対象文字)
		検索対象文字で終わるかどうか
		string str = "test@sample.com";
		if(str.EndsWith(".com"))
		{
		}
	Equals(対象文字)
		完全一致
		string str = "test@sample.com";
		if(str.Equals("test@sample.com"))
		{
		}

■文字列を置換
	Replace(置換前の文字, 置換後の文字);
		string str = "test";
		int a = str.Replace("t", "T");

■文字列の長さ、文字数、バイト数
		string str = "test";
		int a = str.Length;





==================== 配列 ====================
■配列
	文字列型 string [] strArray;
		string [] strArray = textBox1.Text.Replace("\r\n", "\n").Split('\n');

■配列の長さ、文字数、バイト数
	int a = strArray.Length;
	for(int i=0;i<strArray.Length;i++)
	{
	}





==================== ウィンドウ ====================
■メッセージボックス
	MessageBox.Show("test");

■ウィンドウカーソル
	Cursor.Current = Cursors.WaitCursor;
	Cursor.Current = Cursors.Default;

■ウィンドを閉じる
	this.Close();





==================== 情報 ====================
■コンピュータ名、マシンのホスト名
	・コンピュータ名
		System.Environment.MachineName;
	・ホスト名
		System.Net.Dns.GetHostName();





==================== エンコード、デコード ====================
■エンコード、デコード
	・URLエンコード
		string str = "テスト";
		System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("shift_jis");
		str = System.Web.HttpUtility.UrlEncode(str, encoding);
	・URLデコード
		string str = "%83e%83X%83g";
		System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("shift_jis");
		str = System.Web.HttpUtility.UrlDecode(str, encoding);
	・Base64エンコード
		string str = "テスト";
		byte [] byteData = System.Text.Encoding.GetEncoding("shift_jis").GetBytes(str);
		str = System.Convert.ToBase64String(byteData);
	・Base64デコード
		string str = "g2WDWINn";
		byte [] byteData = System.Convert.FromBase64String(str);
		str = System.Text.Encoding.GetEncoding("shift_jis").GetString(byteData);
	・MD5
		string str = "テスト";
		System.Security.Cryptography.MD5CryptoServiceProvider md5 =
				new System.Security.Cryptography.MD5CryptoServiceProvider();
		byte [] byteData =
			md5.ComputeHash(System.Text.Encoding.GetEncoding("shift_jis").GetBytes(str));
			
		string strMD5 = BitConverter.ToString(byteData).ToLower().Replace("-", "");
		str = strMD5;
		
		//System.Text.StringBuilder strMD5 = new System.Text.StringBuilder();
		//foreach (byte b in byteData)
		//{
		//	strMD5.Append(b.ToString("x2"));
		//}
		//str = strMD5.ToString();





このエントリーをはてなブックマークに追加