2020年09月22日 C# memo [長年日記]
_ C# memo
HelloWorld.cs
using System; public class AnyClassYouLike{ static void Main(string[] args){ Console.WriteLine("HelloWorld"); return; } }
変数
sbyte //8ビット整数(符号付き) byte //8ビット整数(符号無し) short //16ビット整数(符号付き) ushort //16ビット整数(符号無し) int //32ビット整数(符号付き) uint //32ビット整数(符号無し) long //64ビット整数(符号付き) ulong //64ビット整数(符号無し) float //32ビット浮動小数(例 123.456f) double //64ビット浮動小数(例 123.456d) char //文字(UNICODE)(例 'あ') bool //論理値 (true or false) decimal //高精度 10進数浮動小数(例 123.456m) string //文字列(UNICODE)(例 "あいうえお") object //全ての型の基底となる型
配列
int[] a = new int[3] {1,2,3}; int[,] a = new int[2,3] {{1,2,3},{4,5,6}};
ハッシュ
using System.Collections; Hashtable ht = new Hashtable(); ht["key1"] = "data1"; // ht.ContainsKey("key1") // True or False // foreach (string key in ht.Keys){ ... }
標準入出力
using System; Console.Write("あいうえお"); // 改行無し Console.WriteLine("あいうえお"); // 改行有り Console.WriteLine("私は{0}{1}です","伊藤","太郎"); string input = Console.ReadLine();
文字列フォーマット
string str = string.Format("{(インデックス)[,(表示幅)][:(書式)(精度)]}", 値) // (インデックス) 0オリジン // ,(表示幅) 整数値、マイナス指定は左寄せ // :(書式)(精度) d 整数値の10進表記、(精度)は桁数を表す(先頭ゼロ埋め) // e 指数表記、(精度)は仮数部の小数点桁数を表す // f 固定小数点表記、(精度)は小数点桁数を表す // n 3桁区切り文字入りの数値表記、(精度)は小数点桁数を表す // x 整数値の16進表記、(精度)は桁数を表す(先頭ゼロ埋め)
string str = string.Format("{(インデックス):###,###,###}", 値) // 可変長、先頭ゼロ埋め無し、桁区切り付き、マイナス符号付き
string str = string.Format("{(インデックス):000,000,000}", 値) // 固定長、先頭ゼロ埋め有り、桁区切り付き、マイナス符号付き
条件分岐
if (a == 1){ }else if (a == 2){ }else{ }
繰返し
using System; using System.Collections; while (a < 10){ } for (int i = 0; i < 10; i++){ } int[] array = new int[10] {1,2,3,4,5,6,7,8,9,10}; foreach (int i in array){ } Hashtable hash = new Hashtable() { {"key1","value1"}, {"key2","value2"}, {"key3","value3"} }; ArrayList list = new ArrayList (hash.Keys); list.Sort(); foreach (string key in list){ }
ファイル入出力(テキスト)
using System.IO; using System.Text; StreamReader sr = new StreamReader("input.csv", Encoding.GetEncoding("UTF-8")); bool append_sw = false; StreamWriter sw = new StreamWriter("output.csv", append_sw, Encoding.GetEncoding("UTF-8")); string str = null; while ((str = sr.ReadLine()) != null){ sw.WriteLine(str); } sr.Close(); sw.Close();
ファイル入出力(バイナリ)
using System.IO; byte[] buf = new byte[1024]; FileStream sr = new FileStream("input.dat", FileMode.Open, FileAccess.Read); FileStream sw = new FileStream("output.dat", FileMode.Create, FileAccess.Write); int readsize = 0; while ((readsize = sr.Read(buf, 0, 1024)) > 0){ sw.Write(buf, 0, readsize); } sr.Close(); sw.Close();
ファイル入出力(バイナリ2)
using System.IO; byte[] buf = new byte[1024]; byte b; FileStream srw = new FileStream("output.dat", FileMode.Open, FileAccess.ReadWrite); int readsize = 0; srw.Seek(10, SeekOrigin.Begin); readsize = srw.Read(buf, 0, 5); b = buf[0];buf[0] = buf[4]; buf[4] = b; b = buf[1];buf[1] = buf[3]; buf[3] = b; srw.Seek(10, SeekOrigin.Begin); srw.Write(buf, 0, 5); srw.Close();
引数
using System; public class AnyClassYouLike{ static void Main(string[] args){ for (int i = 0; i < args.Length; i++){ Console.WriteLine(args[i]); } return; } }
文字列連結
string str = "あいう" + "えお";
文字列分割
using System.Text.RegularExpressions; string input = "aa,bb,,cc,,,dd"; string sep = ",+"; string[] array = Regex.Split(input, sep);
部分文字列
string str = "abcあいうdef"; string hiragana = str.Substring(3, 3);
文字列比較(正規表現)
using System.Text.RegularExpressions; if (Regex.IsMatch("abcdefg", "b.*e")){ ... }
文字列置換(正規表現)
using System.Text.RegularExpressions; string str = Regex.Replace("abcdefg", "b.*f", "b to f"); string str = Regex.Replace("abcdefg", "^(.)(.*)(.)$", "$3$2$1");
文字列⇒数値変換
int i = int.Parse("123"); float f = float.Parse("123.456");
型変換
int i = (int)123.45;
日時取得
DateTime dt; dt = new DateTime(2020,9,20,12,59,59); Console.WriteLine(dt.ToString()); Console.WriteLine(dt.ToString("yyyy/MM/dd HH:mm:ss")); Console.WriteLine(dt.Year); Console.WriteLine(dt.Month); Console.WriteLine(dt.Day); Console.WriteLine(dt.Hour); Console.WriteLine(dt.Minute); Console.WriteLine(dt.Second); dt = DateTime.Parse("2020/09/20 12:59:59"); dt = DateTime.Now; DateTime dt2 = dt.AddYears(10); // AddMonths(), AddDays(), AddHours(), AddMinutes(), AddSeconds() Console.WriteLine(dt.CompareTo(dt2)); // -1 (-1, 0, 1)
外部コマンド実行
using System; using System.Diagnostics; ProcessStartInfo pInfo = new ProcessStartInfo(); pInfo.FileName = "ipconfig.exe"; pInfo.CreateNoWindow = true; // do not open console window pInfo.UseShellExecute = false; // false for console command, true for windows app pInfo.RedirectStandardOutput = true; pInfo.RedirectStandardError = true; pInfo.Arguments = "/all"; Process p = Process.Start(pInfo); p.WaitForExit(); String stdOut = p.StandardOutput.ReadToEnd(); String stdErr = p.StandardError.ReadToEnd(); int exitCode = p.ExitCode; p.Close(); Console.WriteLine(stdOut); Console.WriteLine(stdErr);
終了
Environment.Exit(0);
例外処理
try{ throw new Exception("エラーだよ"); }catch(Exception e){ Console.WriteLine(e); Console.WriteLine(e.Message); }finally{ Console.WriteLine("finally"); }
クラス
using System; public class AnyClassYouLike{ static void Main(string[] args){ MyClass mc = new MyClass("あいう", "えお"); mc.show(); MyClass2 mc2 = new MyClass2("あいう", "えお", "かきくけこ"); mc2.show(); return; } } public class MyClass{ string p1; string p2; public MyClass(){ this.p1 = ""; this.p2 = ""; } public MyClass(string p1, string p2){ this.p1 = p1; this.p2 = p2; } public virtual void show(){ Console.WriteLine(this.p1 + "," + this.p2); } } public class MyClass2 : MyClass{ string p3; public MyClass2(){ } public MyClass2(string p1, string p2, string p3) : base(p1, p2){ this.p3 = p3; } public override void show(){ base.show(); Console.WriteLine(this.p3); } }
インターフェース
using System; public class AnyClassYouLike{ static void Main(string[] args){ Ianimal a; a = new Dog(); a.talk(); a = new Cat(); a.talk(); return; } } interface Ianimal{ void talk(); } class Dog : Ianimal{ public void talk(){ Console.WriteLine("わんわん"); } } class Cat : Ianimal{ public void talk(){ Console.WriteLine("にゃー"); } }
Oracle
using System; using System.Data; using System.Data.OracleClient; public class AnyClassYouLike{ static void Main(string[] args){ string ip = "127.0.0.1"; string user = "mito"; string password = "oracle"; string connectionString = "Data Source=" + ip + ";User ID=" + user + ";Password=" + password + ";Integrated Security=false;"; OracleConnection connection; OracleCommand ocmd; OracleParameter bind_id; OracleParameter bind_name; OracleDataReader ord; int row; // connection = new OracleConnection(connectionString); connection.Open(); ocmd = new OracleCommand(); ocmd.Connection = connection; ocmd.Transaction = connection.BeginTransaction(); // ocmd.CommandText = "insert into t_sample (id,name) values(:id,:name)"; bind_id = new OracleParameter("id", "00000001"); ocmd.Parameters.Add(bind_id); bind_name = new OracleParameter("name", "伊藤 太郎"); ocmd.Parameters.Add(bind_name); row = ocmd.ExecuteNonQuery(); ocmd.Parameters.Remove(bind_id); ocmd.Parameters.Remove(bind_name); ocmd.Transaction.Commit(); // or .Rollback(); ocmd.Transaction = connection.BeginTransaction(); // ocmd.CommandText = "select id,name from t_sample where id >= :id"; bind_id = new OracleParameter("id", "00000000"); ocmd.Parameters.Add(bind_id); ord = ocmd.ExecuteReader(); while (ord.Read()){ Console.WriteLine(ord["id"] + "," + ord["name"]); } ord.Close(); ocmd.Parameters.Remove(bind_id); // ocmd.CommandText = "update t_sample set name=:name where id = :id"; bind_id = new OracleParameter("id", "00000001"); ocmd.Parameters.Add(bind_id); bind_name = new OracleParameter("name", "伊藤 花子"); ocmd.Parameters.Add(bind_name); row = ocmd.ExecuteNonQuery(); ocmd.Parameters.Remove(bind_id); ocmd.Parameters.Remove(bind_name); ocmd.Transaction.Commit(); // or .Rollback(); ocmd.Transaction = connection.BeginTransaction(); // ocmd.CommandText = "select id,name from t_sample where id >= :id"; bind_id = new OracleParameter("id", "00000000"); ocmd.Parameters.Add(bind_id); ord = ocmd.ExecuteReader(); while (ord.Read()){ Console.WriteLine(ord["id"] + "," + ord["name"]); } ord.Close(); ocmd.Parameters.Remove(bind_id); // ocmd.CommandText = "delete from t_sample where id >= :id"; bind_id = new OracleParameter("id", "00000000"); ocmd.Parameters.Add(bind_id); row = ocmd.ExecuteNonQuery(); ocmd.Parameters.Remove(bind_id); ocmd.Transaction.Commit(); // or .Rollback(); // ord.Dispose(); ocmd.Dispose(); connection.Close(); connection.Dispose(); return; } }
MSSQLServer
using System; using System.Data; using System.Data.SqlClient; public class AnyClassYouLike{ static void Main(string[] args){ SqlConnectionStringBuilder builder; SqlConnection con; SqlCommand com; SqlParameter parm_id; SqlParameter parm_name; SqlDataReader reader; SqlTransaction transaction; string sqlstr; builder = new SqlConnectionStringBuilder(); builder.DataSource = "127.0.0.1"; builder.UserID = "mito"; builder.Password = "sqlserver"; builder.InitialCatalog = "testdb"; builder.ConnectTimeout = 15000; // ms con = new SqlConnection(builder.ConnectionString); con.Open(); // sqlstr = "insert into t_sample (id,name) values(@id,@name)"; com = new SqlCommand(sqlstr, con); com.CommandText = sqlstr; transaction = con.BeginTransaction(); com.Transaction = transaction; parm_id = new SqlParameter("@id", "00000001"); com.Parameters.Add(parm_id); parm_name = new SqlParameter("@name", "伊藤 太郎"); com.Parameters.Add(parm_name); com.ExecuteNonQuery(); com.Parameters.Remove(parm_id); com.Parameters.Remove(parm_name); com.Dispose(); transaction.Commit(); // or .Rollback(); // sqlstr = "select id,name from t_sample where id >= @id"; com = new SqlCommand(sqlstr, con); com.CommandText = sqlstr; transaction = con.BeginTransaction(); com.Transaction = transaction; parm_id = new SqlParameter("@id", "00000000"); com.Parameters.Add(parm_id); reader = com.ExecuteReader(); while (reader.Read()){ Console.WriteLine(reader["id"] + "," + reader["name"]); } reader.Close(); com.Parameters.Remove(parm_id); com.Dispose(); transaction.Commit(); // or .Rollback(); // sqlstr = "update t_sample set name=@name where id = @id"; com = new SqlCommand(sqlstr, con); com.CommandText = sqlstr; transaction = con.BeginTransaction(); com.Transaction = transaction; parm_id = new SqlParameter("@id", "00000001"); com.Parameters.Add(parm_id); parm_name = new SqlParameter("@name", "伊藤 花子"); com.Parameters.Add(parm_name); com.ExecuteNonQuery(); com.Parameters.Remove(parm_id); com.Parameters.Remove(parm_name); com.Dispose(); transaction.Commit(); // or .Rollback(); // sqlstr = "select id,name from t_sample where id >= @id"; com = new SqlCommand(sqlstr, con); com.CommandText = sqlstr; transaction = con.BeginTransaction(); com.Transaction = transaction; parm_id = new SqlParameter("@id", "00000000"); com.Parameters.Add(parm_id); reader = com.ExecuteReader(); while (reader.Read()){ Console.WriteLine(reader["id"] + "," + reader["name"]); } reader.Close(); com.Parameters.Remove(parm_id); com.Dispose(); transaction.Commit(); // or .Rollback(); // sqlstr = "delete from t_sample where id >= @id"; com = new SqlCommand(sqlstr, con); com.CommandText = sqlstr; transaction = con.BeginTransaction(); com.Transaction = transaction; parm_id = new SqlParameter("@id", "00000000"); com.Parameters.Add(parm_id); com.ExecuteNonQuery(); com.Parameters.Remove(parm_id); com.Dispose(); transaction.Commit(); // or .Rollback(); // con.Close(); return; } }
Socket通信(echo server (single thread))
using System; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; using System.Text.RegularExpressions; public class AnyClassYouLike{ static void Main(String[] args){ string line; IPAddress ipAdd = IPAddress.Parse("0.0.0.0"); int port = 1234; TcpListener listener = new TcpListener(ipAdd, port); listener.Start(); while (true){ TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("クライアント({0}:{1})と接続しました。", ((IPEndPoint)client.Client.RemoteEndPoint).Address, ((IPEndPoint)client.Client.RemoteEndPoint).Port); NetworkStream ns = client.GetStream(); StreamReader sr = new StreamReader(ns, Encoding.UTF8); StreamWriter sw = new StreamWriter(ns, Encoding.UTF8); while ((line = sr.ReadLine()) != null){ Console.WriteLine(line); sw.WriteLine(line); sw.Flush(); if (Regex.IsMatch(line, "^shutdown")){ break; } } sr.Close(); sw.Close(); ns.Close(); client.Close(); if (line != null){ break; } } listener.Stop(); } }
Socket通信(echo client)
using System; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; public class AnyClassYouLike{ static void Main(String[] args){ string line; string ipAdd = args[0]; int port = int.Parse(args[1]); string str = args[2]; TcpClient client = new TcpClient(ipAdd, port); Console.WriteLine("クライアント({0}:{1})と接続しました。", ((IPEndPoint)client.Client.RemoteEndPoint).Address, ((IPEndPoint)client.Client.RemoteEndPoint).Port); NetworkStream ns = client.GetStream(); StreamReader sr = new StreamReader(ns, Encoding.UTF8); StreamWriter sw = new StreamWriter(ns, Encoding.UTF8); sw.WriteLine(str); sw.Flush(); line = sr.ReadLine(); Console.WriteLine(line); sr.Close(); sw.Close(); ns.Close(); client.Close(); } }
Socket通信(echo server (multi thread))
using System; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; public class AnyClassYouLike{ static void Main(String[] args){ IPAddress ipAdd = IPAddress.Parse("0.0.0.0"); int port = 1234; TcpListener listener = new TcpListener(ipAdd, port); listener.Start(); while (true){ TcpClient client = listener.AcceptTcpClient(); Task.Run(() => communicateClient(client)); Console.WriteLine("クライアント({0}:{1})と接続しました。", ((IPEndPoint)client.Client.RemoteEndPoint).Address, ((IPEndPoint)client.Client.RemoteEndPoint).Port); } listener.Stop(); } private static void communicateClient(TcpClient client){ string line; NetworkStream ns = client.GetStream(); StreamReader sr = new StreamReader(ns, Encoding.UTF8); StreamWriter sw = new StreamWriter(ns, Encoding.UTF8); while ((line = sr.ReadLine()) != null){ Console.WriteLine(line); sw.WriteLine(line); sw.Flush(); } sr.Close(); sw.Close(); ns.Close(); client.Close(); } }