顯示具有 C# 標籤的文章。 顯示所有文章
顯示具有 C# 標籤的文章。 顯示所有文章

2016年10月3日 星期一

[C#] 建立 Log 檔


log4net 套件網址:
http://logging.apache.org/log4net/download_log4net.cgi

log4net 套件名稱:
log4net-1.2.15-bin-newkey

log4net 套件檔案路徑:
log4net-1.2.15\bin\cli\1.0\release



  • 將 log4net.dll 加入到專案目錄下 (記得專案要指定參考此連結檔)
  • 在 assemblyinfo.cs 設定檔中加入
[assembly: log4net.Config.XmlConfigurator(ConfigFile="Log4Net.config", Watch=true)]
  • 複製 Log4Net.config 至專案中

程式碼:
using log4net;  

namespace Log4netExample
{
    public partial class Form1 : Form
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);  

        public Form1()
        {
            InitializeComponent();

            log.Debug("Hello Log");
        }
    }
}

注意:

 Log4Net.config 檔案屬性 => 複製到輸出目錄 需設定成 "有更新時才複製"



產生的 Log 會在專案目錄下的
Log4netExamplenetExa\bin\Debug\applicationLog



Log4net 套件檔案:

Log4Net.config 檔案:

範例檔案:

2016年9月13日 星期二

[C#] DataTable 使用select搜尋並修改欄位

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

//載入DataTable
using System.Data;

namespace DataTable_Select
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a table of five different people.
            // ... Store their size and sex.
            DataTable table = new DataTable("School");
            table.Columns.Add(new DataColumn("Number", typeof(int)));
            table.Columns.Add(new DataColumn("Name", typeof(string)));

            table.Rows.Add(1, "Kevin");
            table.Rows.Add(2, "Justin");
            table.Rows.Add(3, "Chris");
            table.Rows.Add(4, "Fiona");
            table.Rows.Add(5, "John");

            // Search for people above a certain size.
            // ... Require certain sex.
            DataRow[] result = table.Select("Name = 'Fiona'");

            //修改前
            //DataTable table = GetTable(); // 取得資料表
            foreach (DataRow row in table.Rows) // 讀取行
            {
                Console.WriteLine("--- Row ---"); // Print separator.
                foreach (var item in row.ItemArray) // 讀取每個項目
                {
                    Console.Write("Item: "); // Print label.
                    Console.WriteLine(item); // Invokes ToString abstract method.
                }
            }

            //修改中
            for (int i = 0; i < result.Length; i++)
            {
                Console.WriteLine(result[i][0] + "\t" + result[i][1]);
                Console.WriteLine("取得搜尋的行號:"+i);
                result[i][1] = "May";
            }

            //修改後
            //DataTable table = GetTable(); // 取得資料表
            foreach (DataRow row in table.Rows) // 讀取行
            {
                Console.WriteLine("--- Row ---"); // Print separator.
                foreach (var item in row.ItemArray) // 讀取每個項目
                {
                    Console.Write("Item: "); // Print label.
                    Console.WriteLine(item); // Invokes ToString abstract method.
                }
            }

            Console.ReadLine();
        }
    }
}



程式檔案:

[C#] 讀寫XML 並結合 DataTable


目的是設計XML格式並利用 DataTable, 寫入檔案 Default_Setting.xml

再讀取XML格式, 重新寫入 DataTable















using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

//DataTable 載入
using System.Data;
//XElement 載入
using System.Xml.Linq;
//讀取專案路徑
using System.Windows;
//XElement 載入
using System.Xml;

//using System.Data;

namespace XML_Example
{
    class Program
    {
        //讀取專案路徑
        static string ProjectPath = System.Environment.CurrentDirectory + "\\Default_Setting.xml";

        //建立新資料表
        static DataTable SourceDT = new DataTable("SourceDT");

        //讀取XML寫入資料表
        static DataTable NewDT = new DataTable("SourceDT");
     

        private static void Main(string[] args)
        {
            DataTableCreate();
            XMLCreate();
            ReadXML();
            Console.ReadLine();
        }

        /// <summary>
        /// 建立資料表提供XML儲存使用
        /// </summary>
        private static void DataTableCreate()
        {
         
            //建立資料格式
            SourceDT.Columns.Add("Name", typeof(string));
            SourceDT.Columns.Add("Chinese", typeof(string));
            SourceDT.Columns.Add("English", typeof(string));

            //新增資料
            //格式: 姓名 -> 國文成績 -> 英文成績 -> 數學成績
            SourceDT.Rows.Add("Kevin", "male", "ordinary");
            SourceDT.Rows.Add("Justin", "Female", "excellent");

            Console.WriteLine("原始DataTable資料");

            //DataTable table = GetTable(); // 取得資料表
            foreach (DataRow row in SourceDT.Rows) // 讀取行
            {
                Console.WriteLine("--- Row ---"); // Print separator.
                foreach (var item in row.ItemArray) // 讀取每個項目
                {
                    Console.Write("Item: "); // Print label.
                    Console.WriteLine(item); // Invokes ToString abstract method.
                }
            }
        }

        /// <summary>
        /// 利用datatable轉換為XML檔案
        /// </summary>
        private static void XMLCreate()
        {
            XElement Layer1 = new XElement("application");

            XElement Layer2 = new XElement("myClass");

            Layer2.Add(new XAttribute("Name", "Sheep"));
            Layer2.Add(new XElement("ClassRoom", "A-301"));

            foreach (DataRow row in SourceDT.Rows) // 讀取行
            {
                XElement Layer3 = new XElement("ClassMate");

                Layer3.Add(new XAttribute("Name", row[0].ToString()));
                Layer3.Add(new XElement("Gender", row[1].ToString()));
                Layer3.Add(new XElement("Score", row[2].ToString()));
                Layer2.Add(Layer3);
            }

            Layer1.Add(Layer2);

            XDocument xdoc = new XDocument();
            xdoc.Add(Layer1);
            xdoc.Save(ProjectPath);
        }

     

        private static void ReadXML()
        {
            //建立資料格式
            NewDT.Columns.Add("Name", typeof(string));
            NewDT.Columns.Add("Chinese", typeof(string));
            NewDT.Columns.Add("English", typeof(string));


            var allClassMates = XDocument.Load(ProjectPath).Root.Element("myClass").Elements("ClassMate");



            foreach (var person in allClassMates)
            {
                string name = person.Attribute("Name").Value;   // 屬性
                string gender = person.Element("Gender").Value;  // InnerText
                string score = person.Element("Score").Value;    // InnerText

                NewDT.Rows.Add(name, gender, score);
            }

            Console.WriteLine("\nXML讀取寫入DataTable");

            //DataTable table = GetTable(); // 取得資料表
            foreach (DataRow row in NewDT.Rows) // 讀取行
            {
                Console.WriteLine("--- Row ---"); // Print separator.
                foreach (var item in row.ItemArray) // 讀取每個項目
                {
                    Console.Write("Item: "); // Print label.
                    Console.WriteLine(item); // Invokes ToString abstract method.
                }
            }
        }
    }
}


XML檔案路徑:
[專案下]\XML_Example\XML_Example\bin\Debug\Default_Setting.xml


程式檔案:
Link

參考出處:
[C# 3.0] XLinq (Linq for XML Data)
[C#]Linq to XML 讀取XML檔


2016年7月20日 星期三

[C#] 使用 Windows API 讀取 ini 設定檔


專案路徑下新增專案內的
\bin\Debug
裡面新增設定檔 myConfig.ini


using System.Runtime.InteropServices;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern bool WritePrivateProfileString(string sectionName, string keyName, string keyValue, string filePath);

        [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern int GetPrivateProfileString(string sectionName, string keyName, string defaultReturnString, StringBuilder returnString, int returnStringLength, string filePath);


        public Form1()
        {
            InitializeComponent();

            //取得應用程式的可執行檔路徑,不包括檔名,通常都是位於Debug資料夾
            string Rundir = Application.StartupPath + "\\myConfig.ini";

            //建立ini檔案
            WritePrivateProfileString("Owner", "name", "Dan Mac", @"D:\Temp\myConfig.ini");
            WritePrivateProfileString("Owner", "organization", "Apple Inc.", @"D:\Temp\myConfig.ini");
            WritePrivateProfileString("Database", "server", "192.168.1.100", @"D:\Temp\myConfig.ini");
            WritePrivateProfileString("Database", "port", "50000", @"D:\Temp\myConfig.ini");
            WritePrivateProfileString("Database", "file", "\"db.dat\"", @"D:\Temp\myConfig.ini");


            //讀取ini檔案
            StringBuilder data = new StringBuilder(255);
            GetPrivateProfileString("Database", "file", "NA", data, 255, Rundir);
            Console.WriteLine(data);

        }

    }

}

參考出處:
http://einboch.pixnet.net/blog/post/250128728
http://blog.yam.com/phone875/article/25773797

2016年7月17日 星期日

[C#] 新增 Excel 表並寫入測試資料


目前研究C#讀寫取 Excel

解析方式有以下三種:OleDb、Com組件、NPOI


先載入參考

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;



namespace ReadExcel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();


            FileInfo fi = new FileInfo("Data.xls");
            Microsoft.Office.Interop.Excel.Application xlapp = new Microsoft.Office.Interop.Excel.Application();
            if (xlapp == null)
            {
                MessageBox.Show("請安裝office!!");
            }
            xlapp.Visible = false;//不顯示excel程式
            Workbook wb = xlapp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            Worksheet ws = (Worksheet)wb.Sheets[1];
            ws.Name = "English";
            Worksheet ws1 = (Worksheet)wb.Worksheets.Add(Type.Missing, ws, Type.Missing, Type.Missing);//建立一個新分頁
            ws1.Name = "Japanese";
            ws.Cells[1, 1] = "word";
            ws.Cells[1, 2] = "translate";
            ws1.Cells[1, 1] = "word";
            ws1.Cells[1, 2] = "translate";
            ws.Cells[2, 1] = "Hello";
            ws.Cells[2, 2] = "哈囉";
            ws1.Cells[2, 1] = "こんにちは";
            ws1.Cells[2, 2] = "你好";
            if (ws == null || ws1 == null)
            {
                MessageBox.Show("建立sheet失敗");
            }
            wb.SaveAs(@fi.DirectoryName + "\\Data.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel8, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            wb.Close(false, Type.Missing, Type.Missing);
            xlapp.Workbooks.Close();
            xlapp.Quit();
            //刪除 Windows工作管理員中的Excel.exe process,
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlapp);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
        }
    }
}

2016年7月16日 星期六

[C#] DataGridView 資料表測試


使用 C# DataGridView 寫入幾筆資料測試

namespace GridView
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            //dataGridView1.add = "test";
            // Create an unbound DataGridView by declaring a column count.
            dataGridView1.ColumnCount = 4;
            dataGridView1.ColumnHeadersVisible = true;

            // Set the column header names.
            dataGridView1.Columns[0].Name = "Recipe";
            dataGridView1.Columns[1].Name = "Category";
            dataGridView1.Columns[2].Name = "Main Ingredients";
            dataGridView1.Columns[3].Name = "Rating";

            // Populate the rows.
            string[] row1 = new string[] { "Meatloaf", "Main Dish", "ground beef", "**" };
            string[] row2 = new string[] { "Key Lime Pie", "Dessert",  "lime juice, evaporated milk", "****" };
            string[] row3 = new string[] { "Orange-Salsa Pork Chops", "Main Dish", "pork chops, salsa, orange juice", "****" };
            string[] row4 = new string[] { "Black Bean and Rice Salad", "Salad", "black beans, brown rice", "****" };
            string[] row5 = new string[] { "Chocolate Cheesecake", "Dessert", "cream cheese", "***" };
            string[] row6 = new string[] { "Black Bean Dip", "Appetizer", "black beans, sour cream", "***" };
            object[] rows = new object[] { row1, row2, row3, row4, row5, row6 };

            foreach (string[] rowArray in rows)
            {
                dataGridView1.Rows.Add(rowArray);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Resize the height of the column headers.
            dataGridView1.AutoResizeColumnHeadersHeight();

            // Resize all the row heights to fit the contents of all non-header cells.
            dataGridView1.AutoResizeRows(
                DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders);
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}






2016年7月10日 星期日

[C#] 連結 MySQL 測試與應用



安裝MySQL資料庫

http://dev.mysql.com/downloads/windows/installer/


MySQL 官方網站下載 C# 連結 MySQL 動態連結檔
http://dev.mysql.com/downloads/connector/net/6.2.html



namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();

            testconnect();
        }

        private void testconnect()
        {
            string dbHost = "127.0.0.1";
            string dbUser = "root";
            string dbPass = "請輸入您安裝時的密碼";
            string dbName = "sakila";//注意:資料庫

            // 如果有特殊的編碼在database後面請加上;CharSet=編碼, utf8請使用utf8_general_ci
            string connStr = "server=" + dbHost + ";uid=" + dbUser + ";pwd=" + dbPass + ";database=" + dbName;
            MySqlConnection conn = new MySqlConnection(connStr);


            //MySQLCommand commn = new MySQLCommand("set names big5", conn);

            // 連線到資料庫
            try
            {
                conn.Open();
                MessageBox.Show("mysql 連線成功");
            }
            catch 
            { 
                MessageBox.Show("mysql 連線失敗"); 
            }

            //=================//
            // 進行select
            // 執行查詢
            MySqlDataReader myReader = null;
            MySqlCommand myCommand = new MySqlCommand("select * from actor ", conn);//注意:資料表
            myReader = myCommand.ExecuteReader();
            //System.Console.WriteLine(myReader.ToString());

            if (myReader.HasRows)
            {
                while (myReader.Read())
                {
                    Console.WriteLine("{0}\t{1}", myReader.GetInt32(0),
                        myReader.GetString(1));
                }
            }
            else
            {
                Console.WriteLine("No rows found.");
            }

        }
    }
}

參考出處:
http://www.codedata.com.tw/database/mysql-tutorial-database-abc-mysql-installation
https://blog.hsdn.net/1433.html

2016年7月9日 星期六

[C#] Var 的使用與應用



namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Example #1: var is optional because
            // the select clause specifies a string
            string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
            var wordQuery = from word in words
                            where word[0] == 'p'
                            select word;

            // Because each element in the sequence is a string,
            // not an anonymous type, var is optional here also.
            foreach (string s in wordQuery)
            {
                Console.WriteLine(s);
            }

            Console.ReadLine();
        }
    }
}

[C#] Dictionary 的使用與應用



以下透過 Dictionary 實作一個簡單範例

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        Dictionary<string, string> MyDic = new Dictionary<string, string>();

        /*
        Dictionary<string, string> dctNewWay =
        new Dictionary<string, string>()
        {
            {"Key1", "AAAA"}, {"Key2", "BBBB"},
            {"Key3", "CCCC"}, {"Key4", "DDDD"}
        };
        */

        public Form1()
        {
            InitializeComponent();

            CreateDictionary();
            String retrunStr = FindInDictionary("ProductName");
            System.Console.WriteLine(retrunStr);
            ShowAllInDictionary();
        }


        // 建立字典
        private void CreateDictionary()
        {
            MyDic.Add("Name", "Chris");
            MyDic.Add("Brands", "Apple");
            MyDic.Add("ProductName", "iPhone");
            MyDic.Add("Time", DateTime.Now.ToString());
        }

        // 查字典
        private String FindInDictionary(String FindMe)
        {
            if (true == (MyDic.ContainsKey(FindMe)))
            {
                return MyDic[FindMe];
            }
            else
            {
                return "Not Found";
            }
        }

        // 巡整個字典
        private void ShowAllInDictionary()
        {
            foreach (var OneItem in MyDic)
            {
                Console.WriteLine("Key = " + OneItem.Key + ", Value = " + OneItem.Value);
            }
        }
    }
}


參考出處:
http://code2study.blogspot.tw/2012/01/c-dictionary.html

2016年7月6日 星期三

[C#] DataTable 的使用與應用



C# 資料表查詢方式有五種


  1. DataTable.Rows.Find
  2. DataTable.Select
  3. LINQ
  4. DataView
  5. Dictionary

以下透過 DataTable 實作一個簡單範例

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // 這裡我們創建一個DataTable與四列。
            DataTable table = new DataTable();
            table.Columns.Add("Dosage", typeof(int));
            table.Columns.Add("Drug", typeof(string));
            table.Columns.Add("Patient", typeof(string));
            table.Columns.Add("Date", typeof(DateTime));

            // 在這裡,我們新增五筆資料。
            table.Rows.Add(25, "Indocin", "David", DateTime.Now);
            table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
            table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
            table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
            table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);

            //DataTable table = GetTable(); // 取得資料表
            foreach (DataRow row in table.Rows) // 讀取行
            {
                Console.WriteLine("--- Row ---"); // Print separator.
                foreach (var item in row.ItemArray) // 讀取每個項目
                {
                    Console.Write("Item: "); // Print label.
                    Console.WriteLine(item); // Invokes ToString abstract method.
                }
            }

            //讀取每一個項目
            Console.WriteLine(table.Rows[0][0]);

            //修改項目內容
            table.Rows[0][0] = 2;

            //讀取目前的行數
            Console.WriteLine(table.Rows.Count); // Invokes ToString abstract method.

            //讀取目前的列數
            Console.WriteLine(table.Columns.Count); // Invokes ToString abstract method.

            //使用for印出每個項目
            for (int Row = 0; Row < table.Rows.Count; Row++)
            {
                for (int Column = 0; Column < table.Columns.Count; Column++)
                {
                    Console.WriteLine(table.Rows[Row][Column]); // Invokes ToString abstract method.
                }
            }

        }
    }
}


參考出處: