C# : Excel の新しいブックのデフォルトのシートのセルに直接値をセットして、オートフィルを Range オブジェクトから実行する



Range オブジェクトの作成に数値を使用します

プログラミングで処理を行うので、Range("A1:A20") というような表現を使わずに、Cells(行,列) を使って Range オブジェクトを作成しています。
01.using System;
02. 
03.namespace excel_2020_11_26
04.{
05.        class Program
06.        {
07.                static void Main(string[] args)
08.                {
09.                        // Excel アプリケーション
10.                        dynamic ExcelApp = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
11.                        // Excel のパス
12.                        string path = Environment.CurrentDirectory + @"\sample.xlsx";
13. 
14.                        // Excel を表示( 完成したらコメント化 )
15.                        ExcelApp.Visible = true;
16.                        // 警告を出さない
17.                        ExcelApp.DisplayAlerts = false;
18. 
19.                        try
20.                        {
21.                                // ****************************
22.                                // ブック追加
23.                                // ****************************
24.                                dynamic Book = ExcelApp.Workbooks.Add();
25. 
26.                                // 通常一つのシートが作成されています
27.                                dynamic Sheet = Book.Worksheets(1);
28. 
29.                                // ****************************
30.                                // シート名変更
31.                                // ****************************
32.                                Sheet.Name = "C#の処理";
33. 
34.                                // ****************************
35.                                // セルに値を直接セット
36.                                // ****************************
37.                                for (int i = 1; i <= 10; i++)
38.                                {
39.                                        Sheet.Cells(i, 1).Value = "処理 : " + i;
40.                                }
41. 
42.                                // ****************************
43.                                // 1つのセルから
44.                                // AutoFill で値をセット
45.                                // ****************************
46.                                Sheet.Cells(1,2).Value = "子";
47.                                // 基となるセル範囲
48.                                dynamic SourceRange = Sheet.Range(Sheet.Cells(1, 2), Sheet.Cells(1, 2));
49.                                // オートフィルの範囲(基となるセル範囲を含む )
50.                                dynamic FillRange = Sheet.Range(Sheet.Cells(1, 2), Sheet.Cells(10, 2));
51.                                SourceRange.AutoFill(FillRange);
52. 
53. 
54.                                // ****************************
55.                                // 保存
56.                                // ****************************
57.                                Book.SaveAs(path);
58.                        }
59.                        catch (Exception ex)
60.                        {
61.                                ExcelApp.Quit();
62.                                System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp);
63.                                Console.WriteLine(ex.Message);
64.                                return;
65.                        }
66. 
67.                        ExcelApp.Quit();
68.                        // 解放
69.                        System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp);
70. 
71.                        Console.WriteLine("処理を終了します");
72. 
73.                }
74.        }
75.}

関連する記事

JScript : Excel の新しいブックのデフォルトのシートのセルに直接値をセットして、オートフィルを Range オブジェクトから実行する

関連する Microsoft ドキュメント

Application オブジェクト Workbook オブジェクトのコレクション Workbook オブジェクト Worksheet オブジェクトのコレクション Worksheet オブジェクト Cells プロパティ
C#, Excel

シャットダウンダイアログを開く( VBscript, Jscript, C#, C# in PowerShell, PowerShell, PHP, Python, Ruby )

ALT + F4



デスクトップをクリックまたは、デスクトップだけを表示してこのショートカットで開きます。Windows のアプリケーションは通常このショートカットで終了します。(タイトルバーの左上のアイコンをクリックするとメニューが表示されてその中にあります)



VBScript

Shell.ShutdownWindows method

Jscript

C# : VisualStudio
01.using System;
02. 
03.namespace ShutdownDialog
04.{
05.        class Program
06.        {
07.                static void Main(string[] args)
08.                {
09.                        dynamic shell = Activator.CreateInstance(Type.GetTypeFromProgID("shell.application"));
10.                        shell.ShutdownWindows();
11. 
12.                }
13.        }
14.}

PowerShell 内で C#
01.$code = @"
02.using System;
03.public class MyClass {
04.        public static void Main() {
05. 
06.                dynamic shell = Activator.CreateInstance(Type.GetTypeFromProgID("shell.application"));
07.                shell.ShutdownWindows();
08. 
09.        }
10.}
11."@
12. 
13.Add-Type -Language CSharp -TypeDefinition $code -ReferencedAssemblies ("Microsoft.CSharp")
14. 
15.[MyClass]::Main()

PowerShell のみ

PHP

Python
1.import win32com.client
2.shell = win32com.client.Dispatch("shell.application")
3.shell.ShutdownWindows()

pywin32 が必要なので、こちらを参照してください

Ruby





C# : データベースを DataSet クラスで更新する / フィールドに値をセットして Update

更新の SQL を作成せずに、DataRow オブジェクトの中のフィールドに対して個別にデータをセットします。ここでは、 System.Data.SqlClient を使用していますが、OleDb や Odbc でも同じです。

▼ DataAdapter を使用した更新方法のサンプル
DataAdapter.Update(DataSet) Method
▼ 列にデータをセットする方法のサンプル
DataColumn Class
▼ 各オブジェクトの参照方法のサンプル
DataSet.Tables Property
▼ 接続からの全体像
DataSet Class
▼ DataSet 内の Table と言う名称について
複数のselect文をまとめて実行するには?
01.using System;
02.using System.Data;
03.using System.Data.SqlClient;
04. 
05.namespace DBUpdate1
06.{
07.        class Program
08.        {
09.                static void Main(string[] args)
10.                {
11.                        DataSet dataSet = new DataSet();
12.                        string connectionString;
13.                        string queryString = "select * from 社員マスタ where 社員コード = '0001'";
14. 
15.                        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
16.                        // 接続用のパラメータを追加
17.                        builder.Add("Data Source", "layla");
18.                        builder.Add("Initial Catalog", "lightbox");
19.                        builder.Add("User ID", "sa");
20.                        builder.Add("Password", "");
21. 
22.                        // 接続文字列を取得
23.                        connectionString = builder.ConnectionString;
24. 
25.                        using (SqlConnection connection = new SqlConnection(connectionString))
26.                        {
27.                                // 接続
28.                                connection.Open();
29.                                SqlDataAdapter adapter = new SqlDataAdapter();
30.                                // 参照用のマップを追加
31.                                adapter.TableMappings.Add("Table", "社員マスタ");
32. 
33.                                // SQL 作成
34.                                SqlCommand command = new SqlCommand(queryString,connection);
35.                                command.CommandType = CommandType.Text;
36.                                adapter.SelectCommand = command;
37. 
38.                                // 更新用のオブジェクトを準備
39.                                SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adapter);
40. 
41.                                // データを取り出す
42.                                adapter.Fill(dataSet);
43. 
44.                                // テーブルを取得
45.                                DataTable dataTable = dataSet.Tables["社員マスタ"];
46. 
47.                                // 行と列の数( ここでは行は 1 )
48.                                Console.WriteLine($"行数 : {dataTable.Rows.Count}");
49.                                Console.WriteLine($"列数 : {dataTable.Columns.Count}");
50. 
51.                                // 行
52.                                DataRow row = dataTable.Rows[0];
53. 
54.                                // 列の定義
55.                                DataColumn column = dataTable.Columns["氏名"];
56.                                Console.WriteLine($"氏名 : {column.DataType.ToString()}");
57.                                column = dataTable.Columns["給与"];
58.                                Console.WriteLine($"給与 : {column.DataType.ToString()}");
59.                                column = dataTable.Columns["手当"];
60.                                Console.WriteLine($"手当 : {column.DataType.ToString()}");
61.                                column = dataTable.Columns["生年月日"];
62.                                Console.WriteLine($"生年月日 : {column.DataType.ToString()}");
63. 
64.                                // 列の正確なデータの取り出し
65.                                string simei = row.Field<string>("氏名");
66.                                Console.WriteLine(simei);
67.                                int kyuyo = row.Field<int>("給与");
68.                                Console.WriteLine(kyuyo);
69.                                DateTime birth = row.Field<DateTime>("生年月日");
70.                                Console.WriteLine($"{birth.ToShortDateString()}");
71. 
72.                                // データのセット
73.                                row["氏名"] = "山田 太郎";
74.                                // 整数のセット
75.                                row["給与"] = 10000;
76.                                // NULL のセット
77.                                row["手当"] = DBNull.Value;
78.                                // 日付のセット
79.                                row["生年月日"] = DateTime.Parse("1999/01/02");
80. 
81.                                // 更新用のコマンドを取得
82.                                adapter.UpdateCommand = commandBuilder.GetUpdateCommand();
83.                                // 更新実行
84.                                adapter.Update(dataSet);
85.                        }
86. 
87.                        // 一時停止
88.                        Console.ReadLine();
89.                }
90.        }
91.}

更新の無い場合のデータ読み出し

接続準備等は同じなので、パラメータのセットの仕方を別バリエーションで行っています。
001.using System;
002.using System.Data.SqlClient;
003. 
004.namespace DBSelect
005.{
006.        class Program
007.        {
008.                static void Main(string[] args)
009.                {
010.                        string connectionString;
011.                        string queryString = "select * from 社員マスタ order by 社員コード";
012. 
013.                        SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
014.                        // 接続用のパラメータを追加
015.                        builder.Add("Data Source", "layla");
016.                        builder.Add("Initial Catalog", "lightbox");
017.                        builder.Add("User ID", "sa");
018.                        builder.Add("Password", "");
019. 
020.                        // 接続文字列を取得
021.                        connectionString = builder.ConnectionString;
022. 
023.                        using (SqlConnection connection = new SqlConnection(connectionString))
024.                        using (SqlCommand command = new SqlCommand())
025.                        {
026. 
027.                                // *********************
028.                                // 接続
029.                                // *********************
030.                                connection.Open();
031.                                // コマンドオブジェクトに接続をセット
032.                                command.Connection = connection;
033.                                // コマンドを通常 SQL用に変更
034.                                command.CommandType = System.Data.CommandType.Text;
035. 
036.                                // *********************
037.                                // 実行 SQL
038.                                // *********************
039.                                command.CommandText = queryString;
040. 
041.                                // *********************
042.                                // レコードセット取得
043.                                // *********************
044.                                using (SqlDataReader reader = command.ExecuteReader())
045.                                {
046. 
047.                                        // *********************
048.                                        // 列数
049.                                        // *********************
050.                                        int nCols = reader.FieldCount;
051. 
052.                                        // データ取得と表示
053.                                        int row_cnt = 0;
054.                                        while (reader.Read())
055.                                        {
056. 
057.                                                row_cnt++;
058. 
059.                                                // 初回のみ、タイトル文字列を設定
060.                                                if (row_cnt == 1)
061.                                                {
062.                                                        for (int idx = 0; idx < nCols; idx++)
063.                                                        {
064.                                                                Console.Write($"{reader.GetName(idx)}  ");
065.                                                        }
066.                                                        Console.WriteLine();
067.                                                }
068. 
069.                                                // 行データ
070.                                                for (int idx = 0; idx < nCols; idx++)
071.                                                {
072. 
073.                                                        // NULL でない場合
074.                                                        if (!reader.IsDBNull(idx))
075.                                                        {
076.                                                                // 列のデータ型を取得
077.                                                                Type fldType = reader.GetFieldType(idx);
078. 
079.                                                                // 文字列
080.                                                                if (fldType.Name == "String")
081.                                                                {
082.                                                                        Console.Write($"{reader.GetValue(idx).ToString()}  ");
083.                                                                }
084.                                                                else if (fldType.Name == "Int32")
085.                                                                {
086.                                                                        Console.Write($"{reader.GetInt32(idx)}  ");
087.                                                                }
088.                                                                else if (fldType.Name == "DateTime")
089.                                                                {
090.                                                                        Console.Write($"{reader.GetDateTime(idx).ToShortDateString()}  ");
091.                                                                }
092.                                                                else
093.                                                                {
094.                                                                        Console.Write($"{reader.GetValue(idx).ToString()}");
095.                                                                }
096. 
097.                                                        }
098.                                                }
099. 
100.                                                Console.WriteLine();
101. 
102.                                        }
103. 
104.                                        // リーダを使い終わったので閉じる
105.                                        reader.Close();
106. 
107.                                        connection.Close();
108.                                }
109. 
110.                        }       // 最外の using の終わり
111. 
112.                        Console.ReadLine();
113.                }
114.        }
115.}



C# を PowerShell で実行 : Form 内のテキストフィールドに入力した結果をファイルに書き込む

PowerShell のコマンドウインドウで実行すると、2回目以降がエラーになるので、powershell に引数を渡して(バッチファイル)実行させています。

バッチ処理で、どうしても複雑な入力パラメータが必要な時に使えると思います。

関連する記事

C# を PowerShell で実行 : メッセージボックスの応答結果をファイルに書き込む ( バッチファイルで利用可能 )


form1.ps1
01.$code = @"
02.using System;
03.using System.IO;
04.using System.Windows.Forms;
05.public class MyClass {
06. 
07.        // ▼ これは無くても動作する
08.        [STAThread]
09.        public static void Main()
10.        {
11.                // テンプレート部分( 最初から記述されている )
12.                Application.EnableVisualStyles();
13.                Application.SetCompatibleTextRenderingDefault(false);
14.                // Form1 の作成
15.                Application.Run(new Form1());
16.        }
17. 
18.        // Form1 クラス
19.        private class Form1 : Form
20.        {
21.                // コンストラクタ
22.                public Form1()
23.                {
24.                        InitializeComponent();
25.                }
26. 
27.                // 画面作成( デザイナが作成したもの )
28.                private void InitializeComponent()
29.                {
30.                        this.textBox1 = new System.Windows.Forms.TextBox();
31.                        this.button1 = new System.Windows.Forms.Button();
32.                        //
33.                        // textBox1
34.                        //
35.                        this.textBox1.Location = new System.Drawing.Point(47, 49);
36.                        this.textBox1.Name = "textBox1";
37.                        this.textBox1.Size = new System.Drawing.Size(191, 19);
38.                        this.textBox1.TabIndex = 0;
39.                        //
40.                        // button1
41.                        //
42.                        this.button1.Location = new System.Drawing.Point(274, 47);
43.                        this.button1.Name = "button1";
44.                        this.button1.Size = new System.Drawing.Size(75, 23);
45.                        this.button1.TabIndex = 1;
46.                        this.button1.Text = "実行";
47.                        this.button1.UseVisualStyleBackColor = true;
48.                        this.button1.Click += new System.EventHandler(this.button1_Click);
49. 
50.                        //this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
51.                        this.ClientSize = new System.Drawing.Size(400, 150);
52.                        this.Controls.Add(this.button1);
53.                        this.Controls.Add(this.textBox1);
54.                        this.Text = "フォームのタイトル";
55.                        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
56.                }
57. 
58.                // ボタンをクリックした時のイベント
59.                private void button1_Click(object sender, EventArgs e)
60.                {
61.                        Console.WriteLine("button1_Click");
62. 
63.                        // テンポラリフォルダのパスを取得
64.                        string path = Environment.GetEnvironmentVariable("temp");
65. 
66.                        // 書き込むファイルのフルパスを編集する
67.                        string writePath = string.Format( @"{0}\_input_result", path );
68. 
69.                        using (StreamWriter sw = new StreamWriter(writePath, false))
70.                        {
71.                                // 書き込み
72.                                sw.Write( textBox1.Text );
73. 
74.                                // ファイルを閉じます
75.                                sw.Close();
76. 
77.                        }
78. 
79.                        // アプリケーション終了
80.                        Application.Exit();
81.                }
82. 
83.                // コントロール用変数
84.                private System.Windows.Forms.TextBox textBox1;
85.                private System.Windows.Forms.Button button1;
86.        }
87.}
88."@
89. 
90.Add-Type -Language CSharp -TypeDefinition $code -ReferencedAssemblies ("System.Windows.Forms","System.Drawing")
91. 
92.[MyClass]::Main()


form1.bat



C# を PowerShell で実行 : メッセージボックスの応答結果をファイルに書き込む ( バッチファイルで利用可能 )

まずは動作確認の為、VisualStudio でコードを完成させます。
01.using System;
02.using System.IO;
03.using System.Windows.Forms;
04. 
05.namespace MessageBoxConsole
06.{
07.        class Program
08.        {
09.                static void Main(string[] args)
10.                {
11.                        // テンポラリフォルダのパスを取得
12.                        string path = Environment.GetEnvironmentVariable("temp");
13. 
14.                        // 書き込むファイルのフルパスを編集する
15.                        string writePath = $@"{path}\_check_result";
16. 
17.                        // MessageBox を表示する( System.Windows.Forms の参照が必要です )
18.                        // ※ OK か Cancel のボタンが表示されます
19.                        DialogResult check = MessageBox.Show("実行しますか?", "確認", MessageBoxButtons.OKCancel);
20.                        using (StreamWriter sw = new StreamWriter(writePath, false))
21.                        {
22.                                // OK ならば、ファイルに 1 を書き込みます
23.                                if (check == DialogResult.OK)
24.                                {
25.                                        sw.Write("1");
26.                                }
27.                                // CANCEL ならば、ファイルに 0 を書き込みます
28.                                else
29.                                {
30.                                        sw.Write("0");
31.                                }
32. 
33.                                // ファイルを閉じます
34.                                sw.Close();
35. 
36.                        }
37.                }
38.        }
39.}

▼ System.Windows.Forms の参照


次に PowerShell のスクリプトを作成して C# のコードを実行させます。その為に、PowerShell でスクリプトの実行を許可する手順 で設定を済ませておきます。

msgbox.ps1
01.$code = @"
02.using System;
03.using System.IO;
04.using System.Windows.Forms;
05.public class MyClass {
06.        public static void Main() {
07. 
08.                // テンポラリフォルダのパスを取得
09.                string path = Environment.GetEnvironmentVariable("temp");
10. 
11.                // 書き込むファイルのフルパスを編集する
12.                string writePath = string.Format( @"{0}\_check_result", path );
13. 
14.                // MessageBox を表示する( System.Windows.Forms の参照が必要です )
15.                // ※ OK か Cancel のボタンが表示されます
16.                DialogResult check = MessageBox.Show("実行しますか?", "確認", MessageBoxButtons.OKCancel);
17.                using (StreamWriter sw = new StreamWriter(writePath, false))
18.                {
19.                        // OK ならば、ファイルに 1 を書き込みます
20.                        if (check == DialogResult.OK)
21.                        {
22.                                sw.Write("1");
23.                        }
24.                        // CANCEL ならば、ファイルに 0 を書き込みます
25.                        else
26.                        {
27.                                sw.Write("0");
28.                        }
29. 
30.                        // ファイルを閉じます
31.                        sw.Close();
32. 
33.                }
34. 
35.        }
36.}
37."@
38. 
39.Add-Type -Language CSharp -TypeDefinition $code -ReferencedAssemblies ("System.Windows.Forms")
40. 
41.[MyClass]::Main()

テキストファイルに結果を出力しているので、以下のようなバッチファイルで利用する事ができます
01.echo off
02. 
03.echo 処理を開始しました
04. 
05.powershell .\msgbox.ps1
06. 
07.FOR /F %%i IN (%temp%\_check_result) DO (
08.        if "%%i"=="1" goto :ok
09.        if "%%i"=="0" goto :cancel
10.)
11. 
12.:ok
13.echo OK を選択しました
14.goto :end
15. 
16.:cancel
17.echo Cancel を選択しました
18.goto :end
19. 
20. 
21.:end




C# で使用する SQL 文を外部テキストにして String.Format でデータ部分を置き換えて利用する

基本的には、String.Format メソッドのお話ですが、文字列の配列の扱い(ListArrayList)や正規表現のオプションと置換方法が注意事項です。
01.-- ******************************
02.-- 社員マスタ更新
03.-- ******************************
04.  
05.UPDATE 社員マスタ
06.set
07.氏名 = '{1}',
08.給与 = {2},
09.-- 行コメント
10.生年月日 = {3}
11. 
12.--
13.  
14.where 社員コード = '{0}'
15.  
16.-- 行コメント

行コメントは、正規表現で削除します。{} 部分の個数より、配列が大きい必要があり、Nothing が指定されると、{} ごとなくなります。
※ 配列のリサイズが必要な場合は、Array.Resize メソッドで行います。

オンラインの正規表現テストツール

(?m) は複数行モードのオプションです。m に対して s だと単一行モードになります
001.using System;
002.using System.Collections;
003.using System.Collections.Generic;
004.using System.IO;
005.using System.Text;
006. 
007.namespace text_input
008.{
009.        class Program
010.        {
011.                static void Main(string[] args)
012.                {
013.                        // 入力ファイルのパス
014.                        string[] arguments = Environment.GetCommandLineArgs();
015.                        // 引数は一つのみ許可
016.                        if (arguments.Length != 2)
017.                        {
018.                                Console.WriteLine("引数を指定して下さい");
019.                                return;
020.                        }
021. 
022.                        // 引数から取得
023.                        string filePath = arguments[1];
024. 
025.                        // パスを表示
026.                        Console.WriteLine(filePath);
027. 
028.                        // *********************************
029.                        // ▼ 関数呼び出しを記述して、ALT + Enter で自動作成
030.                        // *********************************
031.                        string textData = loadTextData(filePath);
032. 
033.                        // *********************************
034.                        // 行コメントの削除
035.                        // ▼ 正規表現のオプション
036.                        // https://docs.microsoft.com/ja-jp/dotnet/standard/base-types/regular-expression-options
037.                        // *********************************
038.                        string pattern = "(?m)^--.*";   // 複数行モード
039.                        textData = System.Text.RegularExpressions.Regex.Replace(textData, pattern, "");
040. 
041.                        Console.Write(textData);
042. 
043.                        // *********************************
044.                        // 配列の準備(1)
045.                        // *********************************
046.                        string[] data1 = { "0001", "山田太郎", "100000", "'1980/01/01'" };
047.                        Console.WriteLine("配列の数は {0} です", data1.Length);
048. 
049.                        // *********************************
050.                        // 配列を文字列内に埋め込む
051.                        // *********************************
052.                        string sqlResult = String.Format(textData, data1);
053.                        Console.Write(sqlResult);
054. 
055.                        // *********************************
056.                        // 配列の準備(2)
057.                        // *********************************
058.                        string[] data2 = new string[4];
059.                        data2[0] = "0002";
060.                        data2[1] = "山田花子";
061.                        data2[2] = "20000";
062.                        data2[3] = "NULL";
063. 
064.                        // *********************************
065.                        // 配列を文字列内に埋め込む
066.                        // *********************************
067.                        sqlResult = String.Format(textData, data2);
068.                        Console.Write(sqlResult);
069. 
070.                        // *********************************
071.                        // 配列の準備(3)
072.                        // *********************************
073.                        string[] data3 = new string[4];
074.                        data3.SetValue("0003", 0);
075.                        data3.SetValue("山田美子", 1);
076.                        data3.SetValue("30000", 2);
077.                        data3.SetValue("'1980/01/01'", 3);
078. 
079.                        // *********************************
080.                        // 配列を文字列内に埋め込む
081.                        // *********************************
082.                        sqlResult = String.Format(textData, data3);
083.                        Console.Write(sqlResult);
084. 
085.                        // *********************************
086.                        // 配列の準備(4)
087.                        // *********************************
088.                        List<string> data4 = new List<string>();
089.                        data4.Add("0004");
090.                        data4.Add("山田史郎");
091.                        data4.Add("40000");
092.                        data4.Add("'1990/01/01'");
093. 
094.                        // *********************************
095.                        // 配列を文字列内に埋め込む
096.                        // *********************************
097.                        sqlResult = String.Format(textData, data4.ToArray());
098.                        Console.Write(sqlResult);
099. 
100.                        // *********************************
101.                        // 配列の準備(5)
102.                        // ※ 追加するデータ型自由
103.                        // *********************************
104.                        ArrayList data5 = new ArrayList();
105.                        data5.Add("0005");
106.                        data5.Add("山田吾郎");
107.                        data5.Add(50000);
108.                        data5.Add(new DateTime(1995, 1, 1));
109. 
110.                        // *********************************
111.                        // 配列を文字列内に埋め込む
112.                        // 混在なので object 配列
113.                        // *********************************
114.                        object[] strWork = data5.ToArray();
115.                        sqlResult = String.Format(textData, strWork[0], strWork[1], strWork[2], $"'{strWork[3]}'");
116.                        Console.Write(sqlResult);
117. 
118.                        Console.ReadLine();
119. 
120.                }
121. 
122.                private static string loadTextData(string filePath)
123.                {
124. 
125.                        string text = "";
126. 
127.                        // *********************************
128.                        // 主なエンコード
129.                        // *********************************
130.                        // SHIFT_JIS
131.                        // Encoding Enc = Encoding.GetEncoding(932);
132.                        // EUC-JP
133.                        //Encoding Enc = Encoding.GetEncoding(51932);
134.                        // UNICODE 用
135.                        //Encoding Enc = Encoding.GetEncoding(1200);
136.                        // UTF-8N
137.                        Encoding Enc = new UTF8Encoding();
138.                        // UTF-8
139.                        //Encoding Enc = new UTF8Encoding(true);
140. 
141.                        // プロック終了時に開放
142.                        try
143.                        {
144.                                using (StreamReader ReadFile = new StreamReader(filePath, Enc))
145.                                {
146.                                        // 読込み
147.                                        text = ReadFile.ReadToEnd();
148. 
149.                                        // 全て読み込んでいるので閉じる
150.                                        ReadFile.Close();
151. 
152.                                        Console.Write(text);
153.                                }
154. 
155.                        }
156.                        catch (Exception ex)
157.                        {
158.                                Console.WriteLine(ex.Message);
159.                        }
160. 
161.                        return text;
162. 
163.                }
164.        }
165.}

関連する記事

C# : シンプルなテキストファイルの一括入力 / ReadToEnd() : VS2017




C#(コンソール) : ODBC 経由のデータベースの読込み

コンソールから、Windows UI である『ファイル参照ダイアログ』を使用する為に、System.Windows.Forms を参照して [STAThread] を記述しています



概要

ファイル選択をキャンセルした場合は、最初に設定した MySQL に対してアクセスします。ファイル選択で、.xls か .xlsx か .mdb が .accdb を選択すると、それをデータベースとしてアクセスします。
001.using System;
002.using System.Data.Odbc;
003.using System.Diagnostics;
004.using System.Windows.Forms;
005. 
006.namespace DBAccess
007.{
008.        class Program
009.        {
010.                [STAThread]
011.                static void Main(string[] args)
012.                {
013.                        // データベースアクセスに必要なクラス
014.                        OdbcConnection myCon;
015.                        OdbcCommand myCommand;
016.                        OdbcDataReader myReader;
017. 
018.                        // ODBC 接続文字列作成用のクラス
019.                        OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder();
020. 
021.                        // *******************************************
022.                        // インストールされているドライバ文字列
023.                        // 初期は MySQL として準備する
024.                        // *******************************************
025.                        builder.Driver = "MySQL ODBC 8.0 Unicode Driver";
026.                        // builder.Driver = "MySQL ODBC 5.3 Unicode Driver";
027. 
028.                        // 接続用のパラメータを追加
029.                        builder.Add("SERVER", "localhost");
030.                        builder.Add("DATABASE", "lightbox");
031.                        builder.Add("UID", "root");
032.                        builder.Add("PWD", "");
033. 
034.                        // 接続文字列の内容を確認
035.                        Console.WriteLine(builder.ConnectionString);
036. 
037.                        // System.Windows.Forms の参照が必要です
038.                        OpenFileDialog ofd = new OpenFileDialog();
039. 
040.                        // *******************************************
041.                        // ファイル選択した場合はその DB を使用する
042.                        // *******************************************
043.                        ofd.Filter = "AccessとExcel|*.mdb;*.accdb;*.xls;*.xlsx|すべてのファイル(*.*)|*.*";
044.                        ofd.FilterIndex = 1;
045.                        ofd.Title = "データベースを選択してください";
046.                        ofd.RestoreDirectory = true;
047.                        // 選択した場合は再設定する
048.                        if (ofd.ShowDialog() == DialogResult.OK)
049.                        {
050.                                // リセット
051.                                builder.Clear();
052.                                // 拡張子文字列の簡易チェックで Excel か Access が判断する
053.                                if (ofd.FileName.ToLower().IndexOf(".xl") != -1 )
054.                                {
055.                                        // インストールされているドライバ文字列
056.                                        builder.Driver = "Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)";
057.                                }
058.                                else
059.                                {
060.                                        builder.Driver = "Microsoft Access Driver (*.mdb, *.accdb)";
061.                                }
062. 
063.                                // 接続用のパラメータを追加
064.                                builder.Add("dbq", ofd.FileName);
065.                        }
066. 
067.                        // *******************************************
068.                        // 新しい OdbcConnection オブジェクトを作成
069.                        // ( using で使用後の自動解放を行う )
070.                        // https://docs.microsoft.com/ja-jp/dotnet/csharp/language-reference/keywords/using-statement
071.                        // ※ 接続を持続したい場合は using は使わない
072.                        // *******************************************
073.                        using (myCon = new OdbcConnection())
074.                        {
075. 
076.                                // 接続文字列を設定
077.                                myCon.ConnectionString = builder.ConnectionString;
078. 
079.                                // 接続処理
080.                                try
081.                                {
082.                                        // 接続
083.                                        myCon.Open();
084.                                }
085.                                catch (OdbcException ex)
086.                                {
087.                                        // エラー内容( パスワード等でテストする )
088.                                        Console.WriteLine($"Console : {ex.Message}");
089.                                        Debug.WriteLine($"Debug : {ex.Message}");
090.                                }
091. 
092.                                // 接続に失敗している場合は終了
093.                                if (myCon.State != System.Data.ConnectionState.Open)
094.                                {
095.                                        // 終了前に停止
096.                                        Console.ReadLine();
097.                                        return;
098.                                }
099. 
100.                                // *******************************************
101.                                // 接続が完了したので読み出しの準備
102.                                // ▼ 実行する SQL
103.                                // *******************************************
104.                                string myQuery = "select * from 社員マスタ";
105. 
106.                                using (myCommand = new OdbcCommand())
107.                                {
108.                                        // 実行する為に必要な情報をセット
109.                                        myCommand.CommandText = myQuery;
110.                                        myCommand.Connection = myCon;
111. 
112.                                        // *******************************************
113.                                        // 接続と SQL を使用して列データを取り出す
114.                                        // https://docs.microsoft.com/ja-jp/dotnet/api/system.data.odbc.odbcdatareader
115.                                        // *******************************************
116.                                        using (myReader = myCommand.ExecuteReader())
117.                                        {
118. 
119.                                                Console.WriteLine($"定義されている列の数 : {myReader.FieldCount}");
120. 
121.                                                // *******************************************
122.                                                // 列名の一覧
123.                                                // *******************************************
124.                                                for (int i = 0; i < myReader.FieldCount; i++)
125.                                                {
126.                                                        if (i != 0)
127.                                                        {
128.                                                                Console.Write(",");
129.                                                        }
130.                                                        Console.Write(myReader.GetName(i));
131.                                                }
132.                                                // 改行
133.                                                Console.WriteLine();
134. 
135.                                                // *******************************************
136.                                                // データ型の一覧
137.                                                // *******************************************
138.                                                for (int i = 0; i < myReader.FieldCount; i++)
139.                                                {
140.                                                        if (i != 0)
141.                                                        {
142.                                                                Console.Write(",");
143.                                                        }
144.                                                        Console.Write(myReader.GetDataTypeName(i));
145.                                                }
146.                                                // 二つの改行
147.                                                Console.WriteLine("\n");
148. 
149. 
150.                                                // *******************************************
151.                                                // カンマ区切り( CSV ) で出力
152.                                                // *******************************************
153.                                                while (myReader.Read())
154.                                                {
155.                                                        // 文字列
156.                                                        Console.Write($"{GetValue(myReader, "社員コード")},");
157.                                                        Console.Write($"{GetValue(myReader, "氏名")},");
158.                                                        Console.Write($"{GetValue(myReader, "フリガナ")},");
159.                                                        // 整数
160.                                                        Console.Write($"{GetValue(myReader, "給与")},");
161.                                                        Console.Write($"{GetValue(myReader, "手当")},");
162.                                                        // 日付
163.                                                        Console.Write($"{GetValue(myReader, "作成日").Substring(0, 10)},");
164.                                                        Console.Write($"{GetValue(myReader, "更新日")},");
165.                                                        Console.Write(GetValue(myReader, "生年月日"));
166. 
167.                                                        // 改行
168.                                                        Console.WriteLine();
169. 
170.                                                }
171. 
172.                                                myReader.Close();
173. 
174.                                        }
175. 
176.                                        // OdbcCommand に Close はありません
177.                                }
178. 
179.                                // 接続解除
180.                                myCon.Close();
181.                        }
182. 
183.                        // 終了確認用
184.                        Console.WriteLine("\n処理が終了しました");
185. 
186.                        // 終了前に停止
187.                        Console.ReadLine();
188.                }
189. 
190.                // *******************************************
191.                // データを列名文字列で取り出す関数
192.                // *******************************************
193.                static string GetValue(OdbcDataReader myReader, string strName)
194.                {
195. 
196.                        string ret = "";
197.                        int fld = 0;
198. 
199.                        // 指定された列名より、テーブル内での定義順序番号を取得
200.                        fld = myReader.GetOrdinal(strName);
201.                        // 定義順序番号より、NULL かどうかをチェック
202.                        if (myReader.IsDBNull(fld))
203.                        {
204.                                ret = "";
205.                        }
206.                        else
207.                        {
208.                                // NULL でなければ内容をオブジェクトとして取りだして文字列化する
209.                                ret = myReader.GetValue(fld).ToString();
210.                        }
211. 
212.                        // 列の値を返す
213.                        return ret;
214. 
215.                }
216.        }
217.}

関連する記事

32ビット ODBC ドライバの一覧を取得する



C# コンソールアプリを AN HTTPD で実行して WEB の根本を学ぶ

AN HTTP Server の使用方法

単純に、WEB アプリケーション初心者にブラウザとサーバーのやり取りを知ってもらう為に( 今は、開発者ツールがあるので途中の解説がしやすいですし )、C# で作った EXE をそのままブラウザで実行させます。

基本設定

EXE の列の『一般パスでも実行する』にチェックします



次に、一般パスに C# で作成された Debug フォルダを登録します。



後は、loclhost から実行するだけです。

ソースコード
001.using System;
002.using System.Collections;
003.using System.Text;
004.using System.Web;
005. 
006.namespace cgi_test
007.{
008.        class Program
009.        {
010.                static void Main(string[] args)
011.                {
012.                        string formtype = "POST";
013. 
014.                        string[] param = { };
015. 
016.                        // ******************************
017.                        // Console.WriteLine を UTF8 で
018.                        // ******************************
019.                        Console.OutputEncoding = Encoding.UTF8;
020. 
021.                        // ******************************
022.                        // メソッド
023.                        // ******************************
024.                        string method = Environment.GetEnvironmentVariable("REQUEST_METHOD");
025. 
026.                        // ******************************
027.                        // GET
028.                        // ******************************
029.                        if (method == "GET")
030.                        {
031.                                // ******************************
032.                                // QUERY_STRING
033.                                // ******************************
034.                                string query_string = System.Environment.GetEnvironmentVariable("QUERY_STRING");
035.                                // URL のみの場合はデータ無しの QUERY_STRING を用意する
036.                                if (query_string == "" )
037.                                {
038.                                        query_string = "field1=&field2=";
039.                                }
040. 
041.                                // & で分割して key=value の文字列の配列を作成する
042.                                param = query_string.Split('&');
043.                        }
044. 
045.                        // ******************************
046.                        // POST
047.                        // ******************************
048.                        if (method == "POST")
049.                        {
050.                                string line;
051. 
052.                                // POST 時は必ず key=value の文字列が存在する
053.                                line = Console.ReadLine();
054.                                param = line.Split('&');
055.                        }
056. 
057.                        // = で区切って key と value が配列の 0 と 1 にセットされる
058.                        string[] key_value = { };
059. 
060.                        // ******************************
061.                        // key と value の格納
062.                        // ******************************
063.                        Hashtable field = new Hashtable();
064. 
065.                        foreach (string key_value_set in param)
066.                        {
067.                                key_value = key_value_set.Split('=');
068.                                // key がある場合は、Hashtable に格納する
069.                                if (key_value[0] != "") {
070.                                        // System.Web を参照して using System.Web; で HttpUtility.UrlDecode
071.                                        // %エンコードを元に戻す
072.                                        field.Add(key_value[0], HttpUtility.UrlDecode(key_value[1]));
073.                                }
074.                        }
075. 
076.                        // ******************************
077.                        // HTTP ヘッダ
078.                        // PHP の session_cache_limiter
079.                        // ******************************
080.                        Console.WriteLine("Content-Type: text/html; charset=utf-8");
081.                        Console.WriteLine("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
082.                        Console.WriteLine("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
083.                        Console.WriteLine("Pragma: no-cache");
084.                        Console.WriteLine();
085. 
086.                        string message = "<div>こんにちは世界</div>";
087. 
088.                        // ******************************
089.                        // HTML
090.                        // $ で変数埋め込みのヒアドキュメント
091.                        // ******************************
092.                        string html = $@"<!DOCTYPE html>
093.<html>
094.<head>
095.</head>
096.<body>
097.{message}
098.<form method='{formtype}'>
099.<p>氏名 : <input type='text' name='field1' value='{field["field1"]}'></p>
100.<p>フリガナ : <input type='text' name='field2' value='{field["field2"]}'></p>
101.<p>送信 : <input type='submit' name='send' value='送信'></p>
102.</form>
103.</body>
104.</html>";
105. 
106.                        // 作成した HTML を出力する
107.                        Console.WriteLine(html);
108.                }
109.        }
110.}




C# : 現在実行中のパスのファイルの一覧をテキストファイル(UTF8N)に出力する

Microsoft のドキュメントに 方法: ディレクトリとファイルを列挙する というページがあります。そこでは、Directory.EnumerateDirectories を使用したサンプルですが、 List クラスに変換してから foreach を使用しています。

foreach を使用して一覧を取得するだけならば、戻り値の IEnumerable をそのまま使用しても問題無いですが( Directory.EnumerateFiles のサンプルはそのまま使用している )、一般的な認識として List クラスを使用したほうが良いと思います。

※ IEnumerable は Interface であり、クラスを新たに作成する時に使用するものです
※ $ は、文字列補間
※ @ は、逐語的識別子として機能します

01.using System;
02.using System.Collections.Generic;
03.using System.IO;
04.using System.Text;
05. 
06.namespace file_list
07.{
08.        class Program
09.        {
10.                static void Main(string[] args)
11.                {
12.                        // 現在実行中のパス
13.                        string cur_path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
14. 
15.                        // 文字列補間 / https://docs.microsoft.com/ja-jp/dotnet/csharp/language-reference/tokens/interpolated
16.                        Console.WriteLine( $"現在実行中のパスは {cur_path} です" );
17. 
18.                        // **********************************************
19.                        // 一覧処理は、IEnumerable のままでも可能ですが、
20.                        // 一般的なコードとして処理する為に
21.                        // List クラスを使用します
22.                        // **********************************************
23.                        List<string> files = new List<string>(Directory.EnumerateFiles(cur_path, "*", SearchOption.TopDirectoryOnly));
24. 
25.                        // 情報を一括で処理する為に文字列としてメモリに保存します
26.                        StringBuilder file_list = new StringBuilder();
27. 
28.                        foreach ( string name in files)
29.                        {
30.                                // ファイルのパスを追加
31.                                file_list.Append(name);
32.                                // 改行を追加
33.                                file_list.AppendLine();
34.                        }
35. 
36.                        // コマンドプロンプトに表示
37.                        Console.Write(file_list.ToString());
38. 
39.                        // 同じ内容をテキストファイルに UTF8N で書き込み
40.                        Encoding enc = new UTF8Encoding();
41. 
42.                        // 書き込むファイル( ドキュメントフォルダ )
43.                        string write_path = string.Format($@"{Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)}\cs_file_list.txt");
44. 
45.                        // 追加書き込み( false で上書き )
46.                        try
47.                        {
48.                                using (StreamWriter write_file = new StreamWriter(write_path, false, enc))
49.                                {
50.                                        // 書き込み
51.                                        write_file.Write(file_list.ToString());
52. 
53.                                        // UTF8N 確認の為
54.                                        write_file.WriteLine("日本語表示");
55. 
56.                                        // 閉じる
57.                                        write_file.Close();
58.                                }
59. 
60.                        }
61.                        catch (Exception ex)
62.                        {
63.                                Console.WriteLine(ex.Message);
64.                        }
65.                        // **********************************************
66.                        // try ブロックは
67.                        // 編集メニュー > IntelliSense > ブロックの挿入
68.                        // **********************************************
69. 
70.                        Console.ReadLine();
71.                }
72.        }
73.}

🔻 テキストエディタのタブを保持する設定


※ 変換は全てコピー > 削除 > 貼り付け


C# : シンプルなテキストファイルの一括入力 / ReadToEnd() : VS2017

ファイル読み込み部分を囲む try ブロックは、編集メニュー > IntelliSense > ブロックの挿入を使用します。

入力ファイルは、プロジェクトのプロパティよりデバッグタブを選択して『コマンドライン引数』のテキストエリアに、エクスプローラで Shift キーを押しながら右クリックで表示される『パスのコピー』で得られるダブルクォーテーションで囲まれたパスを貼り付けます。



🔻 引数よりパスを取得
string[] arguments = Environment.GetCommandLineArgs();

🔻 ローカルウインドウによる表示

🔻 イミディエイトウインドウによる表示

🔻 デバックに必要なウインドウは、デバッグ中に以下の場所から表示させる事ができます

using の実装は、赤い波線上で ALT+Enter で候補が表示されます

01.using System;
02.using System.IO;
03.using System.Text;
04. 
05.namespace text_input
06.{
07.    class Program
08.    {
09.        static void Main(string[] args)
10.        {
11.            // 入力ファイルのパス
12.            string[] arguments = Environment.GetCommandLineArgs();
13.            // 引数は一つのみ許可
14.            if (arguments.Length != 2)
15.            {
16.                Console.WriteLine("引数を指定して下さい");
17.                return;
18.            }
19. 
20.            // 引数から取得
21.            string FilePath = arguments[1];
22. 
23.            // パスを表示
24.            Console.WriteLine(FilePath);
25. 
26. 
27.            // *********************************
28.            // 主なエンコード
29.            // *********************************
30.            // SHIFT_JIS
31.            Encoding Enc = Encoding.GetEncoding(932);
32. 
33.            // EUC-JP
34.            //Encoding Enc = Encoding.GetEncoding(51932);
35.            // UNICODE 用
36.            //Encoding Enc = Encoding.GetEncoding(1200);
37.            // UTF-8N
38.            //Encoding Enc = new UTF8Encoding();
39.            // UTF-8
40.            //Encoding Enc = new UTF8Encoding(true);
41. 
42.            // プロック終了時に開放
43.            try
44.            {
45.                using (StreamReader ReadFile = new StreamReader(FilePath, Enc))
46.                {
47.                    // 読込み
48.                    string Text = ReadFile.ReadToEnd();
49. 
50.                    // 全て読み込んでいるので閉じる
51.                    ReadFile.Close();
52. 
53.                    Console.WriteLine(Text);
54.                }
55. 
56.            }
57.            catch (Exception ex)
58.            {
59.                Console.WriteLine(ex.Message);
60.            }
61. 
62.            Console.ReadLine();
63. 
64.        }
65.    }
66.}