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



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

プログラミングで処理を行うので、Range("A1:A20") というような表現を使わずに、Cells(行,列) を使って Range オブジェクトを作成しています。
using System;

namespace excel_2020_11_26
{
	class Program
	{
		static void Main(string[] args)
		{
			// Excel アプリケーション
			dynamic ExcelApp = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));
			// Excel のパス
			string path = Environment.CurrentDirectory + @"\sample.xlsx";

			// Excel を表示( 完成したらコメント化 )
			ExcelApp.Visible = true;
			// 警告を出さない
			ExcelApp.DisplayAlerts = false;

			try
			{
				// ****************************
				// ブック追加
				// ****************************
				dynamic Book = ExcelApp.Workbooks.Add();

				// 通常一つのシートが作成されています
				dynamic Sheet = Book.Worksheets(1);

				// ****************************
				// シート名変更
				// ****************************
				Sheet.Name = "C#の処理";

				// ****************************
				// セルに値を直接セット
				// ****************************
				for (int i = 1; i <= 10; i++)
				{
					Sheet.Cells(i, 1).Value = "処理 : " + i;
				}

				// ****************************
				// 1つのセルから
				// AutoFill で値をセット
				// ****************************
				Sheet.Cells(1,2).Value = "子";
				// 基となるセル範囲
				dynamic SourceRange = Sheet.Range(Sheet.Cells(1, 2), Sheet.Cells(1, 2));
				// オートフィルの範囲(基となるセル範囲を含む )
				dynamic FillRange = Sheet.Range(Sheet.Cells(1, 2), Sheet.Cells(10, 2));
				SourceRange.AutoFill(FillRange);


				// ****************************
				// 保存
				// ****************************
				Book.SaveAs(path);
			}
			catch (Exception ex)
			{
				ExcelApp.Quit();
				System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp);
				Console.WriteLine(ex.Message);
				return;
			}

			ExcelApp.Quit();
			// 解放
			System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp);

			Console.WriteLine("処理を終了します");

		}
	}
}


関連する記事

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
set objShell = CreateObject("shell.application")
call objShell.ShutdownWindows()

Shell.ShutdownWindows method

Jscript
var objShell = new ActiveXObject("shell.application");
objShell.ShutdownWindows();


C# : VisualStudio
using System;

namespace ShutdownDialog
{
	class Program
	{
		static void Main(string[] args)
		{
			dynamic shell = Activator.CreateInstance(Type.GetTypeFromProgID("shell.application"));
			shell.ShutdownWindows();

		}
	}
}


PowerShell 内で C#
$code = @"
using System;
public class MyClass {
	public static void Main() {

		dynamic shell = Activator.CreateInstance(Type.GetTypeFromProgID("shell.application"));
		shell.ShutdownWindows();

	}
}
"@

Add-Type -Language CSharp -TypeDefinition $code -ReferencedAssemblies ("Microsoft.CSharp")

[MyClass]::Main()


PowerShell のみ
$shell = New-Object -ComObject Shell.Application
$shell.ShutdownWindows()


PHP
<?php
$shell = new COM( "shell.application" );
$shell->ShutdownWindows();
?>


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

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

Ruby
require 'win32ole'
shell = WIN32OLE.new('shell.application')
shell.ShutdownWindows()






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文をまとめて実行するには?
using System;
using System.Data;
using System.Data.SqlClient;

namespace DBUpdate1
{
	class Program
	{
		static void Main(string[] args)
		{
			DataSet dataSet = new DataSet();
			string connectionString;
			string queryString = "select * from 社員マスタ where 社員コード = '0001'";

			SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
			// 接続用のパラメータを追加
			builder.Add("Data Source", "layla");
			builder.Add("Initial Catalog", "lightbox");
			builder.Add("User ID", "sa");
			builder.Add("Password", "");

			// 接続文字列を取得
			connectionString = builder.ConnectionString;

			using (SqlConnection connection = new SqlConnection(connectionString))
			{
				// 接続
				connection.Open();
				SqlDataAdapter adapter = new SqlDataAdapter();
				// 参照用のマップを追加
				adapter.TableMappings.Add("Table", "社員マスタ");

				// SQL 作成
				SqlCommand command = new SqlCommand(queryString,connection);
				command.CommandType = CommandType.Text;
				adapter.SelectCommand = command;

				// 更新用のオブジェクトを準備
				SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adapter);

				// データを取り出す
				adapter.Fill(dataSet);

				// テーブルを取得
				DataTable dataTable = dataSet.Tables["社員マスタ"];

				// 行と列の数( ここでは行は 1 )
				Console.WriteLine($"行数 : {dataTable.Rows.Count}");
				Console.WriteLine($"列数 : {dataTable.Columns.Count}");

				// 行
				DataRow row = dataTable.Rows[0];

				// 列の定義
				DataColumn column = dataTable.Columns["氏名"];
				Console.WriteLine($"氏名 : {column.DataType.ToString()}");
				column = dataTable.Columns["給与"];
				Console.WriteLine($"給与 : {column.DataType.ToString()}");
				column = dataTable.Columns["手当"];
				Console.WriteLine($"手当 : {column.DataType.ToString()}");
				column = dataTable.Columns["生年月日"];
				Console.WriteLine($"生年月日 : {column.DataType.ToString()}");

				// 列の正確なデータの取り出し
				string simei = row.Field<string>("氏名");
				Console.WriteLine(simei);
				int kyuyo = row.Field<int>("給与");
				Console.WriteLine(kyuyo);
				DateTime birth = row.Field<DateTime>("生年月日");
				Console.WriteLine($"{birth.ToShortDateString()}");

				// データのセット
				row["氏名"] = "山田 太郎";
				// 整数のセット
				row["給与"] = 10000;
				// NULL のセット
				row["手当"] = DBNull.Value;
				// 日付のセット
				row["生年月日"] = DateTime.Parse("1999/01/02");

				// 更新用のコマンドを取得
				adapter.UpdateCommand = commandBuilder.GetUpdateCommand();
				// 更新実行
				adapter.Update(dataSet);
			}

			// 一時停止
			Console.ReadLine();
		}
	}
}


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

接続準備等は同じなので、パラメータのセットの仕方を別バリエーションで行っています。
using System;
using System.Data.SqlClient;

namespace DBSelect
{
	class Program
	{
		static void Main(string[] args)
		{
			string connectionString;
			string queryString = "select * from 社員マスタ order by 社員コード";

			SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
			// 接続用のパラメータを追加
			builder.Add("Data Source", "layla");
			builder.Add("Initial Catalog", "lightbox");
			builder.Add("User ID", "sa");
			builder.Add("Password", "");

			// 接続文字列を取得
			connectionString = builder.ConnectionString;

			using (SqlConnection connection = new SqlConnection(connectionString))
			using (SqlCommand command = new SqlCommand())
			{

				// *********************
				// 接続
				// *********************
				connection.Open();
				// コマンドオブジェクトに接続をセット
				command.Connection = connection;
				// コマンドを通常 SQL用に変更
				command.CommandType = System.Data.CommandType.Text;

				// *********************
				// 実行 SQL
				// *********************
				command.CommandText = queryString;

				// *********************
				// レコードセット取得
				// *********************
				using (SqlDataReader reader = command.ExecuteReader())
				{

					// *********************
					// 列数
					// *********************
					int nCols = reader.FieldCount;

					// データ取得と表示
					int row_cnt = 0;
					while (reader.Read())
					{

						row_cnt++;

						// 初回のみ、タイトル文字列を設定
						if (row_cnt == 1)
						{
							for (int idx = 0; idx < nCols; idx++)
							{
								Console.Write($"{reader.GetName(idx)}  ");
							}
							Console.WriteLine();
						}

						// 行データ
						for (int idx = 0; idx < nCols; idx++)
						{

							// NULL でない場合
							if (!reader.IsDBNull(idx))
							{
								// 列のデータ型を取得
								Type fldType = reader.GetFieldType(idx);

								// 文字列
								if (fldType.Name == "String")
								{
									Console.Write($"{reader.GetValue(idx).ToString()}  ");
								}
								else if (fldType.Name == "Int32")
								{
									Console.Write($"{reader.GetInt32(idx)}  ");
								}
								else if (fldType.Name == "DateTime")
								{
									Console.Write($"{reader.GetDateTime(idx).ToShortDateString()}  ");
								}
								else
								{
									Console.Write($"{reader.GetValue(idx).ToString()}");
								}

							}
						}

						Console.WriteLine();

					}

					// リーダを使い終わったので閉じる
					reader.Close();

					connection.Close();
				}

			}       // 最外の using の終わり

			Console.ReadLine();
		}
	}
}




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

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

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

関連する記事

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


form1.ps1
$code = @"
using System;
using System.IO;
using System.Windows.Forms;
public class MyClass {

	// ▼ これは無くても動作する
	[STAThread]
	public static void Main()
	{
		// テンプレート部分( 最初から記述されている )
		Application.EnableVisualStyles();
		Application.SetCompatibleTextRenderingDefault(false);
		// Form1 の作成
		Application.Run(new Form1());
	}

	// Form1 クラス
	private class Form1 : Form
	{
		// コンストラクタ
		public Form1()
		{
			InitializeComponent();
		}

		// 画面作成( デザイナが作成したもの )
		private void InitializeComponent()
		{
			this.textBox1 = new System.Windows.Forms.TextBox();
			this.button1 = new System.Windows.Forms.Button();
			// 
			// textBox1
			// 
			this.textBox1.Location = new System.Drawing.Point(47, 49);
			this.textBox1.Name = "textBox1";
			this.textBox1.Size = new System.Drawing.Size(191, 19);
			this.textBox1.TabIndex = 0;
			// 
			// button1
			// 
			this.button1.Location = new System.Drawing.Point(274, 47);
			this.button1.Name = "button1";
			this.button1.Size = new System.Drawing.Size(75, 23);
			this.button1.TabIndex = 1;
			this.button1.Text = "実行";
			this.button1.UseVisualStyleBackColor = true;
			this.button1.Click += new System.EventHandler(this.button1_Click);

			//this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(400, 150);
			this.Controls.Add(this.button1);
			this.Controls.Add(this.textBox1);
			this.Text = "フォームのタイトル";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
		}

		// ボタンをクリックした時のイベント
		private void button1_Click(object sender, EventArgs e)
		{
			Console.WriteLine("button1_Click");

			// テンポラリフォルダのパスを取得
			string path = Environment.GetEnvironmentVariable("temp");

			// 書き込むファイルのフルパスを編集する
			string writePath = string.Format( @"{0}\_input_result", path );

			using (StreamWriter sw = new StreamWriter(writePath, false))
			{
				// 書き込み
				sw.Write( textBox1.Text );

				// ファイルを閉じます
				sw.Close();

			}

			// アプリケーション終了
			Application.Exit();
		}

		// コントロール用変数
		private System.Windows.Forms.TextBox textBox1;
		private System.Windows.Forms.Button button1;
	}
}
"@

Add-Type -Language CSharp -TypeDefinition $code -ReferencedAssemblies ("System.Windows.Forms","System.Drawing")

[MyClass]::Main()



form1.bat
@powershell -NoProfile -ExecutionPolicy Unrestricted "./form1.ps1"



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

まずは動作確認の為、VisualStudio でコードを完成させます。
using System;
using System.IO;
using System.Windows.Forms;

namespace MessageBoxConsole
{
	class Program
	{
		static void Main(string[] args)
		{
			// テンポラリフォルダのパスを取得
			string path = Environment.GetEnvironmentVariable("temp");

			// 書き込むファイルのフルパスを編集する
			string writePath = $@"{path}\_check_result";

			// MessageBox を表示する( System.Windows.Forms の参照が必要です )
			// ※ OK か Cancel のボタンが表示されます
			DialogResult check = MessageBox.Show("実行しますか?", "確認", MessageBoxButtons.OKCancel);
			using (StreamWriter sw = new StreamWriter(writePath, false))
			{
				// OK ならば、ファイルに 1 を書き込みます
				if (check == DialogResult.OK)
				{
					sw.Write("1");
				}
				// CANCEL ならば、ファイルに 0 を書き込みます
				else
				{
					sw.Write("0");
				}

				// ファイルを閉じます
				sw.Close();

			}
		}
	}
}

▼ System.Windows.Forms の参照


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

msgbox.ps1
$code = @"
using System;
using System.IO;
using System.Windows.Forms;
public class MyClass {
	public static void Main() {

		// テンポラリフォルダのパスを取得
		string path = Environment.GetEnvironmentVariable("temp");

		// 書き込むファイルのフルパスを編集する
		string writePath = string.Format( @"{0}\_check_result", path );

		// MessageBox を表示する( System.Windows.Forms の参照が必要です )
		// ※ OK か Cancel のボタンが表示されます
		DialogResult check = MessageBox.Show("実行しますか?", "確認", MessageBoxButtons.OKCancel);
		using (StreamWriter sw = new StreamWriter(writePath, false))
		{
			// OK ならば、ファイルに 1 を書き込みます
			if (check == DialogResult.OK)
			{
				sw.Write("1");
			}
			// CANCEL ならば、ファイルに 0 を書き込みます
			else
			{
				sw.Write("0");
			}

			// ファイルを閉じます
			sw.Close();

		}

	}
}
"@

Add-Type -Language CSharp -TypeDefinition $code -ReferencedAssemblies ("System.Windows.Forms")

[MyClass]::Main()


テキストファイルに結果を出力しているので、以下のようなバッチファイルで利用する事ができます
echo off

echo 処理を開始しました

powershell .\msgbox.ps1

FOR /F %%i IN (%temp%\_check_result) DO (
	if "%%i"=="1" goto :ok
	if "%%i"=="0" goto :cancel
)

:ok
echo OK を選択しました
goto :end

:cancel
echo Cancel を選択しました
goto :end


:end





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

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

--
 
where 社員コード = '{0}'
 
-- 行コメント

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

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

(?m) は複数行モードのオプションです。m に対して s だと単一行モードになります
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace text_input
{
	class Program
	{
		static void Main(string[] args)
		{
			// 入力ファイルのパス
			string[] arguments = Environment.GetCommandLineArgs();
			// 引数は一つのみ許可
			if (arguments.Length != 2)
			{
				Console.WriteLine("引数を指定して下さい");
				return;
			}

			// 引数から取得
			string filePath = arguments[1];

			// パスを表示
			Console.WriteLine(filePath);

			// *********************************
			// ▼ 関数呼び出しを記述して、ALT + Enter で自動作成
			// *********************************
			string textData = loadTextData(filePath);

			// *********************************
			// 行コメントの削除
			// ▼ 正規表現のオプション
			// https://docs.microsoft.com/ja-jp/dotnet/standard/base-types/regular-expression-options
			// *********************************
			string pattern = "(?m)^--.*";   // 複数行モード
			textData = System.Text.RegularExpressions.Regex.Replace(textData, pattern, "");

			Console.Write(textData);

			// *********************************
			// 配列の準備(1)
			// *********************************
			string[] data1 = { "0001", "山田太郎", "100000", "'1980/01/01'" };
			Console.WriteLine("配列の数は {0} です", data1.Length);

			// *********************************
			// 配列を文字列内に埋め込む
			// *********************************
			string sqlResult = String.Format(textData, data1);
			Console.Write(sqlResult);

			// *********************************
			// 配列の準備(2)
			// *********************************
			string[] data2 = new string[4];
			data2[0] = "0002";
			data2[1] = "山田花子";
			data2[2] = "20000";
			data2[3] = "NULL";

			// *********************************
			// 配列を文字列内に埋め込む
			// *********************************
			sqlResult = String.Format(textData, data2);
			Console.Write(sqlResult);

			// *********************************
			// 配列の準備(3)
			// *********************************
			string[] data3 = new string[4];
			data3.SetValue("0003", 0);
			data3.SetValue("山田美子", 1);
			data3.SetValue("30000", 2);
			data3.SetValue("'1980/01/01'", 3);

			// *********************************
			// 配列を文字列内に埋め込む
			// *********************************
			sqlResult = String.Format(textData, data3);
			Console.Write(sqlResult);

			// *********************************
			// 配列の準備(4)
			// *********************************
			List<string> data4 = new List<string>();
			data4.Add("0004");
			data4.Add("山田史郎");
			data4.Add("40000");
			data4.Add("'1990/01/01'");

			// *********************************
			// 配列を文字列内に埋め込む
			// *********************************
			sqlResult = String.Format(textData, data4.ToArray());
			Console.Write(sqlResult);

			// *********************************
			// 配列の準備(5)
			// ※ 追加するデータ型自由
			// *********************************
			ArrayList data5 = new ArrayList();
			data5.Add("0005");
			data5.Add("山田吾郎");
			data5.Add(50000);
			data5.Add(new DateTime(1995, 1, 1));

			// *********************************
			// 配列を文字列内に埋め込む
			// 混在なので object 配列
			// *********************************
			object[] strWork = data5.ToArray();
			sqlResult = String.Format(textData, strWork[0], strWork[1], strWork[2], $"'{strWork[3]}'");
			Console.Write(sqlResult);

			Console.ReadLine();

		}

		private static string loadTextData(string filePath)
		{

			string text = "";

			// *********************************
			// 主なエンコード
			// *********************************
			// SHIFT_JIS
			// Encoding Enc = Encoding.GetEncoding(932);
			// EUC-JP
			//Encoding Enc = Encoding.GetEncoding(51932);
			// UNICODE 用
			//Encoding Enc = Encoding.GetEncoding(1200);
			// UTF-8N
			Encoding Enc = new UTF8Encoding();
			// UTF-8
			//Encoding Enc = new UTF8Encoding(true);

			// プロック終了時に開放
			try
			{
				using (StreamReader ReadFile = new StreamReader(filePath, Enc))
				{
					// 読込み
					text = ReadFile.ReadToEnd();

					// 全て読み込んでいるので閉じる
					ReadFile.Close();

					Console.Write(text);
				}

			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}

			return text;

		}
	}
}


関連する記事

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




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

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



概要

ファイル選択をキャンセルした場合は、最初に設定した MySQL に対してアクセスします。ファイル選択で、.xls か .xlsx か .mdb が .accdb を選択すると、それをデータベースとしてアクセスします。
using System;
using System.Data.Odbc;
using System.Diagnostics;
using System.Windows.Forms;

namespace DBAccess
{
	class Program
	{
		[STAThread]
		static void Main(string[] args)
		{
			// データベースアクセスに必要なクラス
			OdbcConnection myCon;
			OdbcCommand myCommand;
			OdbcDataReader myReader;

			// ODBC 接続文字列作成用のクラス
			OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder();

			// *******************************************
			// インストールされているドライバ文字列
			// 初期は MySQL として準備する
			// *******************************************
			builder.Driver = "MySQL ODBC 8.0 Unicode Driver";
			// builder.Driver = "MySQL ODBC 5.3 Unicode Driver";

			// 接続用のパラメータを追加
			builder.Add("SERVER", "localhost");
			builder.Add("DATABASE", "lightbox");
			builder.Add("UID", "root");
			builder.Add("PWD", "");

			// 接続文字列の内容を確認
			Console.WriteLine(builder.ConnectionString);

			// System.Windows.Forms の参照が必要です
			OpenFileDialog ofd = new OpenFileDialog();

			// *******************************************
			// ファイル選択した場合はその DB を使用する
			// *******************************************
			ofd.Filter = "AccessとExcel|*.mdb;*.accdb;*.xls;*.xlsx|すべてのファイル(*.*)|*.*";
			ofd.FilterIndex = 1;
			ofd.Title = "データベースを選択してください";
			ofd.RestoreDirectory = true;
			// 選択した場合は再設定する
			if (ofd.ShowDialog() == DialogResult.OK)
			{
				// リセット
				builder.Clear();
				// 拡張子文字列の簡易チェックで Excel か Access が判断する
				if (ofd.FileName.ToLower().IndexOf(".xl") != -1 )
				{
					// インストールされているドライバ文字列
					builder.Driver = "Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)";
				}
				else
				{
					builder.Driver = "Microsoft Access Driver (*.mdb, *.accdb)";
				}

				// 接続用のパラメータを追加
				builder.Add("dbq", ofd.FileName);
			}

			// *******************************************
			// 新しい OdbcConnection オブジェクトを作成
			// ( using で使用後の自動解放を行う )
			// https://docs.microsoft.com/ja-jp/dotnet/csharp/language-reference/keywords/using-statement
			// ※ 接続を持続したい場合は using は使わない
			// *******************************************
			using (myCon = new OdbcConnection())
			{

				// 接続文字列を設定
				myCon.ConnectionString = builder.ConnectionString;

				// 接続処理
				try
				{
					// 接続
					myCon.Open();
				}
				catch (OdbcException ex)
				{
					// エラー内容( パスワード等でテストする )
					Console.WriteLine($"Console : {ex.Message}");
					Debug.WriteLine($"Debug : {ex.Message}");
				}

				// 接続に失敗している場合は終了
				if (myCon.State != System.Data.ConnectionState.Open)
				{
					// 終了前に停止
					Console.ReadLine();
					return;
				}

				// *******************************************
				// 接続が完了したので読み出しの準備
				// ▼ 実行する SQL
				// *******************************************
				string myQuery = "select * from 社員マスタ";

				using (myCommand = new OdbcCommand())
				{
					// 実行する為に必要な情報をセット
					myCommand.CommandText = myQuery;
					myCommand.Connection = myCon;

					// *******************************************
					// 接続と SQL を使用して列データを取り出す
					// https://docs.microsoft.com/ja-jp/dotnet/api/system.data.odbc.odbcdatareader
					// *******************************************
					using (myReader = myCommand.ExecuteReader())
					{

						Console.WriteLine($"定義されている列の数 : {myReader.FieldCount}");

						// *******************************************
						// 列名の一覧
						// *******************************************
						for (int i = 0; i < myReader.FieldCount; i++)
						{
							if (i != 0)
							{
								Console.Write(",");
							}
							Console.Write(myReader.GetName(i));
						}
						// 改行
						Console.WriteLine();

						// *******************************************
						// データ型の一覧
						// *******************************************
						for (int i = 0; i < myReader.FieldCount; i++)
						{
							if (i != 0)
							{
								Console.Write(",");
							}
							Console.Write(myReader.GetDataTypeName(i));
						}
						// 二つの改行 
						Console.WriteLine("\n");


						// *******************************************
						// カンマ区切り( CSV ) で出力
						// *******************************************
						while (myReader.Read())
						{
							// 文字列
							Console.Write($"{GetValue(myReader, "社員コード")},");
							Console.Write($"{GetValue(myReader, "氏名")},");
							Console.Write($"{GetValue(myReader, "フリガナ")},");
							// 整数
							Console.Write($"{GetValue(myReader, "給与")},");
							Console.Write($"{GetValue(myReader, "手当")},");
							// 日付
							Console.Write($"{GetValue(myReader, "作成日").Substring(0, 10)},");
							Console.Write($"{GetValue(myReader, "更新日")},");
							Console.Write(GetValue(myReader, "生年月日"));

							// 改行
							Console.WriteLine();

						}

						myReader.Close();

					}

					// OdbcCommand に Close はありません
				}

				// 接続解除
				myCon.Close();
			}

			// 終了確認用
			Console.WriteLine("\n処理が終了しました");

			// 終了前に停止
			Console.ReadLine();
		}

		// *******************************************
		// データを列名文字列で取り出す関数
		// *******************************************
		static string GetValue(OdbcDataReader myReader, string strName)
		{

			string ret = "";
			int fld = 0;

			// 指定された列名より、テーブル内での定義順序番号を取得
			fld = myReader.GetOrdinal(strName);
			// 定義順序番号より、NULL かどうかをチェック
			if (myReader.IsDBNull(fld))
			{
				ret = "";
			}
			else
			{
				// NULL でなければ内容をオブジェクトとして取りだして文字列化する
				ret = myReader.GetValue(fld).ToString();
			}

			// 列の値を返す
			return ret;

		}
	}
}


関連する記事

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



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

AN HTTP Server の使用方法

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

基本設定

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



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



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

ソースコード
using System;
using System.Collections;
using System.Text;
using System.Web;

namespace cgi_test
{
	class Program
	{
		static void Main(string[] args)
		{
			string formtype = "POST";

			string[] param = { };

			// ******************************
			// Console.WriteLine を UTF8 で
			// ******************************
			Console.OutputEncoding = Encoding.UTF8;

			// ******************************
			// メソッド
			// ******************************
			string method = Environment.GetEnvironmentVariable("REQUEST_METHOD");

			// ******************************
			// GET
			// ******************************
			if (method == "GET")
			{
				// ******************************
				// QUERY_STRING
				// ******************************
				string query_string = System.Environment.GetEnvironmentVariable("QUERY_STRING");
				// URL のみの場合はデータ無しの QUERY_STRING を用意する
				if (query_string == "" )
				{
					query_string = "field1=&field2=";
				}

				// & で分割して key=value の文字列の配列を作成する
				param = query_string.Split('&');
			}

			// ******************************
			// POST
			// ******************************
			if (method == "POST")
			{
				string line;

				// POST 時は必ず key=value の文字列が存在する
				line = Console.ReadLine();
				param = line.Split('&');
			}

			// = で区切って key と value が配列の 0 と 1 にセットされる
			string[] key_value = { };

			// ******************************
			// key と value の格納
			// ******************************
			Hashtable field = new Hashtable();

			foreach (string key_value_set in param)
			{
				key_value = key_value_set.Split('=');
				// key がある場合は、Hashtable に格納する
				if (key_value[0] != "") {
					// System.Web を参照して using System.Web; で HttpUtility.UrlDecode
					// %エンコードを元に戻す
					field.Add(key_value[0], HttpUtility.UrlDecode(key_value[1]));
				}
			}

			// ******************************
			// HTTP ヘッダ
			// PHP の session_cache_limiter
			// ******************************
			Console.WriteLine("Content-Type: text/html; charset=utf-8");
			Console.WriteLine("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
			Console.WriteLine("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
			Console.WriteLine("Pragma: no-cache");
			Console.WriteLine();

			string message = "<div>こんにちは世界</div>";

			// ******************************
			// HTML
			// $ で変数埋め込みのヒアドキュメント
			// ******************************
			string html = $@"<!DOCTYPE html>
<html>
<head>
</head>
<body>
{message}
<form method='{formtype}'>
<p>氏名 : <input type='text' name='field1' value='{field["field1"]}'></p>
<p>フリガナ : <input type='text' name='field2' value='{field["field2"]}'></p>
<p>送信 : <input type='submit' name='send' value='送信'></p>
</form>
</body>
</html>";

			// 作成した HTML を出力する
			Console.WriteLine(html);
		}
	}
}





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

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

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

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

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace file_list
{
	class Program
	{
		static void Main(string[] args)
		{
			// 現在実行中のパス
			string cur_path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

			// 文字列補間 / https://docs.microsoft.com/ja-jp/dotnet/csharp/language-reference/tokens/interpolated
			Console.WriteLine( $"現在実行中のパスは {cur_path} です" );

			// **********************************************
			// 一覧処理は、IEnumerable のままでも可能ですが、
			// 一般的なコードとして処理する為に 
			// List クラスを使用します
			// **********************************************
			List<string> files = new List<string>(Directory.EnumerateFiles(cur_path, "*", SearchOption.TopDirectoryOnly));

			// 情報を一括で処理する為に文字列としてメモリに保存します
			StringBuilder file_list = new StringBuilder();

			foreach ( string name in files)
			{
				// ファイルのパスを追加
				file_list.Append(name);
				// 改行を追加
				file_list.AppendLine();
			}

			// コマンドプロンプトに表示
			Console.Write(file_list.ToString());

			// 同じ内容をテキストファイルに UTF8N で書き込み
			Encoding enc = new UTF8Encoding();

			// 書き込むファイル( ドキュメントフォルダ )
			string write_path = string.Format($@"{Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)}\cs_file_list.txt");

			// 追加書き込み( false で上書き )
			try
			{
				using (StreamWriter write_file = new StreamWriter(write_path, false, enc))
				{
					// 書き込み
					write_file.Write(file_list.ToString());

					// UTF8N 確認の為
					write_file.WriteLine("日本語表示");

					// 閉じる
					write_file.Close();
				}

			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
			// **********************************************
			// try ブロックは
			// 編集メニュー > IntelliSense > ブロックの挿入
			// **********************************************

			Console.ReadLine();
		}
	}
}


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


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


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

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

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



🔻 引数よりパスを取得
string[] arguments = Environment.GetCommandLineArgs();
🔻 ローカルウインドウによる表示 🔻 イミディエイトウインドウによる表示 🔻 デバックに必要なウインドウは、デバッグ中に以下の場所から表示させる事ができます using の実装は、赤い波線上で ALT+Enter で候補が表示されます
using System;
using System.IO;
using System.Text;

namespace text_input
{
    class Program
    {
        static void Main(string[] args)
        {
            // 入力ファイルのパス
            string[] arguments = Environment.GetCommandLineArgs();
            // 引数は一つのみ許可
            if (arguments.Length != 2)
            {
                Console.WriteLine("引数を指定して下さい");
                return;
            }

            // 引数から取得
            string FilePath = arguments[1];

            // パスを表示
            Console.WriteLine(FilePath);


            // *********************************
            // 主なエンコード
            // *********************************
            // SHIFT_JIS
            Encoding Enc = Encoding.GetEncoding(932);

            // EUC-JP
            //Encoding Enc = Encoding.GetEncoding(51932);
            // UNICODE 用
            //Encoding Enc = Encoding.GetEncoding(1200);
            // UTF-8N
            //Encoding Enc = new UTF8Encoding();
            // UTF-8
            //Encoding Enc = new UTF8Encoding(true);

            // プロック終了時に開放
            try
            {
                using (StreamReader ReadFile = new StreamReader(FilePath, Enc))
                {
                    // 読込み
                    string Text = ReadFile.ReadToEnd();

                    // 全て読み込んでいるので閉じる
                    ReadFile.Close();

                    Console.WriteLine(Text);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadLine();

        }
    }
}