顯示具有 C#學習筆記 標籤的文章。 顯示所有文章
顯示具有 C#學習筆記 標籤的文章。 顯示所有文章

2013年2月5日 星期二

030-確認字串是否為有效的電子郵件格式

網路上搜尋來的email驗證,一直沒法完整擋掉有格式問題的郵件,所以只好自己上網練功,結果......研究老半天原來微軟有給範例= =",不過正規表示式 Regular Expression這個還是得要會一點,PO文繼續練功

 

http://msdn.microsoft.com/zh-tw/library/01escwtf.aspx

 

記得using System.Text.RegularExpressions;

2012年12月13日 星期四

029-發送HTML類型且有夾帶附件的郵件主旨會亂碼

msg.SubjectEncoding = System.Text.Encoding.UTF8;//郵件標題編碼                                     
msg.BodyEncoding = System.Text.Encoding.UTF8;//郵件內容編碼
msg.Subject = "您好";//郵件標題
msg.IsBodyHtml = true;//是否是HTML郵件
attach = new Attachment(c:\test.txt);                                            attach.NameEncoding = System.Text.Encoding.UTF8;                                            msg.Attachments.Add(attach);

msg.Body = "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=utf-8\">"; //加上這一段後,發送HTML類型且有夾帶附件的郵件,在Outlook Express查看郵件原始碼就會是Content-Type: text/html; charset=utf-8而不是Content-Type: text/plain; charset=us-ascii,郵件主旨也不會有亂碼的出現。

2012年11月6日 星期二

028-字串或二進位資料會被截斷

INSERT INTO DB 或 UPDATE DB 時如果發現這個問題,可能就是 table 的某個欄位設的太小了。
比如說要INSERT INTO 6個字元的字串,結果欄位大小只設了5個字元,就會有這樣的字串或二進位資料被截斷的問題產生,解決辦法就是放寬欄位不然就是截取符合該欄位的大小資料寫入DB
但我今天遇到的問題是,X = "-180°";
這樣一個字串在C# Length為5但在寫入DB為6,但DB欄位限定5,
X.Substring(0, 5);//寫入失敗
可能要用char方式抓出再組成字串解?
待續...



目前想到可行的解法為
CONVERT(VARCHAR(5), X)

2012年3月16日 星期五

027-資料夾、檔案複製(簡易備份)

using System.IO;
using System.Diagnostics;

string today = DateTime.Today.Year.ToString().Trim() + DateTime.Today.Month.ToString().PadLeft(2, '0').Trim() + DateTime.Today.Day.ToString().PadLeft(2, '0').Trim();
string sourcePath = @"來源路徑\";
string targetPath = @"目的路徑\";

for (int i = 1; i < 1000; i++)
{
    if (Directory.Exists(targetPath + "INVMB_REP" + today + i.ToString().PadLeft(3, '0')))
    {
        if (Directory.Exists(targetPath + "INVMB_REP" + today + (i + 1).ToString().PadLeft(3, '0')) == false)
        {
            Directory.CreateDirectory(targetPath + "INVMB_REP" + today + (i + 1).ToString().PadLeft(3, '0'));
            targetPath = targetPath + "INVMB_REP" + today + (i + 1).ToString().PadLeft(3, '0');
            break;
        }
    }
    else
    {
        Directory.CreateDirectory(targetPath + "INVMB_REP" + today + "001");
        targetPath = targetPath + "INVMB_REP" + today + "001";
        break;
    }
}
CopyDirectory(sourcePath, targetPath);

MessageBox.Show("檔案已備份完成","ahhsu的程式備份");

//開啟資料夾     
ProcessStartInfo startInfo = new ProcessStartInfo("explorer.exe");
startInfo.Arguments = targetPath;

Process.Start(startInfo);

 

 

 

public static void CopyDirectory(string srcFolder, string dstFolder)
{
    if (Directory.Exists(srcFolder) == true)
    {
        if (Directory.Exists(dstFolder) == false)
            Directory.CreateDirectory(dstFolder);

        DirectoryInfo srcDirectory = new DirectoryInfo(srcFolder);
        foreach (FileInfo fi in srcDirectory.GetFiles())
        {
            try { System.IO.File.Copy(fi.FullName, dstFolder + Path.DirectorySeparatorChar + fi.Name); }
            catch { }
        }
        foreach (DirectoryInfo di in srcDirectory.GetDirectories())
        {
            try { CopyDirectory(di.FullName, dstFolder + Path.DirectorySeparatorChar + di.Name); }
            catch { }
        }
    }
}

2012年3月15日 星期四

026-開啟資料夾

using System.Diagnostics;

ProcessStartInfo startInfo = new ProcessStartInfo("explorer.exe");
startInfo.Arguments = "C:\資料夾名稱";
Process.Start(startInfo);

2012年2月18日 星期六

025-string.Format輸出格式

//數字字串不足,前面補0
String.Format("{0:00000}", 123); // 輸出 00123
String.Format("{0:D5}", 123); // 輸出 00123

//數字字串不足,前後都補0
String.Format("{0:00000.0000}", 123.45); // 輸出 00125.4500

//每3位數加逗號
String.Format("{0:0,0}", 0); // 輸出 00
String.Format("{0:0,0}", 1234567); // 輸出 1,234,567  //缺點:當數字=0時,會顯示 00
String.Format("{0:N}", 1234567); // 輸出 1,234,567.00
String.Format("{0:N0}", 1234567); // 輸出 1,234,567
String.Format("{0:N4}", 1234567); // 輸出 1,234,567.0000

//電話號碼
String.Format("{0:(###) ####-####}", 12345678901); // 輸出(123)4567-8901

//金額表示方式
String.Format("{0:C}", 0); // 輸出 NT$0.00
String.Format("{0:C}", 12345)); // 輸出 NT$12,345.00
String.Format("{0:$#,##0.00;($#,##0.00);Zero}", 0); // 輸出 Zero
String.Format("{0:$#,##0.00;($#,##0.00);Zero}", 1234.50); // 輸出 $1,234.50

//百分比
String.Format("{0:0%}", 10 / (float)50); // 輸出 20%

//取小數第4位,並對第5位做四捨五入
String.Format("{0:#,0.####}", 1234.56789); // 1,234.5679

//小數點不足4位不補0
String.Format("{0:0.####}", 1234.567); // 1234.567

//到小數2位的百分比
String.Format("{0:0.00%}", 10 / (float)50); // 輸出 20.00%

2012年2月10日 星期五

024-ini檔的資料讀取和寫入

using System;
using System.Text;

using System.Runtime.InteropServices;

namespace InTransferStock //和引用CINI的namespace名稱要一樣不然會出錯
{
    class CINI:IDisposable
    {
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        private bool bDisposed = false;
        private string _FilePath = string.Empty;
        public string FilePath
        {
            get
            {
                if (_FilePath == null)
                    return string.Empty;
                else
                    return _FilePath;
            }
            set
            {
                if (_FilePath != value)
                    _FilePath = value;
            }
        }
                /// <summary>
        /// 建構子。
        /// </summary>
        /// <param name="path">檔案路徑。</param>     
        public CINI(string path)
        {
            _FilePath = path;
        }
        /// <summary>
        /// 解構子。
        /// </summary>
        ~CINI()
        {
            Dispose(false);
        }

        /// <summary>
        /// 釋放資源(程式設計師呼叫)。
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this); //要求系統不要呼叫指定物件的完成項。
        }
        /// <summary>
        /// 釋放資源(給系統呼叫的)。
        /// </summary>       
        protected virtual void Dispose(bool IsDisposing)
        {
            if (bDisposed)
            {
                return;
            }

            if (IsDisposing)
            {

            }

            bDisposed = true;
        }

        /// <summary>
        /// 設定 KeyValue 值。
        /// </summary>
        /// <param name="IN_Section">Section。</param>
        /// <param name="IN_Key">Key。</param>
        /// <param name="IN_Value">Value。</param>
        public void setKeyValue(string IN_Section, string IN_Key, string IN_Value)
        {
            WritePrivateProfileString(IN_Section, IN_Key, IN_Value, this._FilePath);
        }

        /// <summary>
        /// 取得 Key 相對的 Value 值。
        /// </summary>
        /// <param name="IN_Section">Section。</param>
        /// <param name="IN_Key">Key。</param>       
        public string getKeyValue(string IN_Section, string IN_Key)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(IN_Section, IN_Key, "", temp, 255, this._FilePath);
            return temp.ToString();
        }

        /// <summary>
        /// 取得 Key 相對的 Value 值,若沒有則使用預設值(DefaultValue)。
        /// </summary>
        /// <param name="Section">Section。</param>
        /// <param name="Key">Key。</param>
        /// <param name="DefaultValue">DefaultValue。</param>       
        public string getKeyValue(string Section, string Key, string DefaultValue)
        {
            StringBuilder sbResult = null;

            try
            {
                sbResult = new StringBuilder(255);

                GetPrivateProfileString(Section, Key, "", sbResult, 255, this._FilePath);

                return (sbResult.Length > 0) ? sbResult.ToString() : DefaultValue;
            }
            catch
            {
                return string.Empty;
            }
        }
    }
}

 

 

先將↑內容存成CINI.cs

引用之前必須加上
using Microsoft.Win32;

//讀取INI檔內的資料
using (CINI myCINI = new CINI(Path.Combine(Application.StartupPath, @"InTransferStock.ini")))   //ini的路徑和名稱請自行修改
{
    Password = myCINI.getKeyValue("EMAIL", "PWD");
}

//將資料寫入INI檔
using (CINI myCINI = new CINI(Path.Combine(Application.StartupPath, @"InTransferStock.ini"))) //ini的路徑和名稱請自行修改
{
    myCINI.setKeyValue("EMAIL", "PWD", edtPwd.Text.Trim());
}

 

2012年2月9日 星期四

023-Excel匯入資料庫

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//連接Excel使用
using System.Data.OleDb;
//連接SQL使用
using System.Data.SqlClient;

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

        private void button1_Click(object sender, EventArgs e)
        {
            string xlsPath = ""; string sheetName = "";
            xlsPath = @"C:\ImportFile.xls";
            sheetName = "Sheet1";
            //呼叫ImportDB函式
            ImportDB(xlsPath, sheetName);
        }

        //宣告靜態函式
        protected static void ImportDB(string xlsPath, string sheetName)
        {
            int i=0;
            //Excel的連線字串,HDR代表是否用第一列作欄位名稱,IMEX=1代表利用讀取用
            //xlsx格式不適用
            //using (OleDbConnection conn = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + xlsPath + "';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"))
            using (OleDbConnection conn = new OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + xlsPath + "';Extended Properties='Excel 12.0 Xml;HDR=Yes;IMEX=1'"))
            {
                //開啟OLEDB連結
                conn.Open();
                //類似T-SQL語法
                OleDbCommand cmd = new OleDbCommand("SELECT [品號] FROM [" + sheetName + "$];", conn);
                //執行讀取
                OleDbDataReader reader = cmd.ExecuteReader();

                //方法一
                //SQL連線字串,此例使用檔案型資料庫
                using (SqlConnection cn = new SqlConnection(@"Data Source= 主機位址;Initial catalog=選用DB;User id =帳號;Password =密碼"))//連線字串請自輸填入
                {
                    //開啟SQL連結
                    cn.Open();
                    //宣告交易,並指定連線
                    SqlTransaction stran = cn.BeginTransaction();
                    //利用例外處理包起來,使用一次Commit以達到類似批次處理效果
                    try
                    {
                        //逐列讀取直到結束
                        while (reader.Read())
                        {
                            //T-SQL新增語法
                            SqlCommand scmd = new SqlCommand(@"UPDATE INVMB SET MB051 = 0,USR_GROUP = 'DS120201' WHERE MB001 = '" + reader[0] + "'", cn); //自行輸入SQL語法
                            //宣告命令所使用的交易
                            scmd.Transaction = stran;
                            //執行命令,但未真正進入資料庫,Commit後才真正進入
                            scmd.ExecuteNonQuery();
                        }
                        //迴圈跑完一次匯入
                        stran.Commit();
                    }
                    //例外
                    catch (SqlException ex)
                    {
                        MessageBox.Show(ex.Message);
                        MessageBox.Show(ex.Number);
                        stran.Rollback();
                    }
                    catch (OleDbException ex)
                    {
                        MessageBox.Show(ex.Message);
                        stran.Rollback();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        stran.Rollback();
                    }
                    //不管有無例外發生皆會執行
                    finally
                    {
                        //關閉連結和OleDbDataReader
                        cn.Close();
                        conn.Close();
                        reader.Close();
                        MessageBox.Show("已完成匯入...");
                    }
                }
            }
        }
    }
}

2012年2月8日 星期三

022-讀寫Regedit 方法

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;

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

        //讀取測試
        private void button1_Click(object sender, EventArgs e)
        {
            string subKeyPath = @"Software\Microsoft\Internet Account Manager\Accounts\00000005";
            string keyName = "POP3 User Name";
            if (HaveReg(subKeyPath))
            {
                MessageBox.Show(ReadReg(subKeyPath, keyName));
            }
            else
            {
                MessageBox.Show(subKeyPath + "路徑不存在");
            }
        }

        //寫入測試
        private void button2_Click(object sender, EventArgs e)
        {
            string subKeyPath = @"Software\Microsoft\Internet Account Manager\Accounts\00000005";
            string keyName = "POP3 User Password";
            string keyValue = "Andy";
            if (WriteReg(subKeyPath, keyName, keyValue))
            {
                MessageBox.Show("寫入成功");
            }
            else
            {
                MessageBox.Show("寫入失敗");
            }
        }

        // 讀取 Regedit
        public static string ReadReg(string SubKeyPath, string keyName)
        {
        string keyValue = "";

        try
        {
            RegistryKey rootKey = Registry.CurrentUser; //Registry參數
            RegistryKey subKey = rootKey.OpenSubKey(SubKeyPath);
            keyValue = subKey.GetValue(keyName).ToString();
            subKey.Close();
            rootKey.Close();
        }
        catch (Exception)
        {
        }
        return keyValue;
        }

        public static Boolean HaveReg(string keyPath)
        {
            Boolean returnValue = false;
            try
            {
                RegistryKey rootKey = Registry.CurrentUser;
                RegistryKey subKey = rootKey.OpenSubKey(@keyPath);

                //不存在
                if (subKey == null)
                {
                    returnValue = false;
                }
                else
                {
                    returnValue = true;
                }
                subKey.Close();
                rootKey.Close();
            }
            catch (Exception)
            {
            }
            return returnValue;
        }

        // 寫入 Regedit
        public static Boolean WriteReg(string subKeyPath, string keyName, string keyValue)
        {
            Boolean returnValue = false;
            try
            {
                RegistryKey rootKey = Registry.CurrentUser;
                RegistryKey subKey = rootKey.OpenSubKey(@subKeyPath);

                //不存在,Create
                if (subKey == null)
                {
                rootKey.CreateSubKey(subKeyPath);
                }

                //寫入資料
                subKey = rootKey.OpenSubKey(subKeyPath, true);
                subKey.SetValue(keyName, keyValue);
                returnValue = true;
                subKey.Close();
                rootKey.Close();
            }
            catch (Exception)
            {
            }
            return returnValue;
        }

    }
}

2012年1月9日 星期一

021-Form1 Form2互相傳值

Form1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(this);
f2.ShowDialog();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.ColumnCount = 3;
}
}
}
Form2
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication4
{
public partial class Form2 : Form
{
public Form2(Form1 f1)
{
InitializeComponent();
this.Tag = f1;
}
private void Form2_Load(object sender, EventArgs e)
{
dataGridView1.ColumnCount = 2;
dataGridView1.Columns[0].Width = 50;
dataGridView1.Columns[0].HeaderText = "GG";
dataGridView1.Columns[1].HeaderText = "YY";
dataGridView1.Rows.Add("1", "1");
dataGridView1.Rows.Add("2", "2");
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
((Form1)this.Tag).dataGridView1.Rows.Add(dataGridView1.Rows[i].Cells[0].Value, dataGridView1.Rows[i].Cells[1].Value,"未執行");
}
this.Close();
}

}
}

2011年8月31日 星期三

019-System.Net.Dns.GetHostByName(string) 已過時

編譯時出現System.Net.Dns.GetHostByName(string) 已過時

改成Dns.GetHostEntry(Dns.GetHostName());

2011年8月30日 星期二

018-maskedTextBox元件

這個元件可以讓讓user輸入文字而不將重要的 / 覆蓋過去,當然還有其它作用請自行測試。

2011年8月28日 星期日

020-Console暫停程式方法

在程式最後加上Console.ReadLine();

2011年8月20日 星期六

017-維護紀錄範例

/*************************************************************************
** 撰寫者:Andy(Andy) 撰寫日期:2011/08/19
** 用途: 1.
** 做法:
** 1.
** 注意事項:
** 1.
** 2.
** 維護記錄:
** 維護者:姓名(員工代號) 維護日期:日期
** 維護項目:
** 1.
** 2.
** 做法: 1.
** 2.
** 注意事項:
** 1.
*************************************************************************/

2011年8月19日 星期五

016-讓程式暫停

using System.Threading ;

 

//讓程式暫停3秒
Thread.Sleep(3000);

2011年7月27日 星期三

015-時間到提醒該關機休息

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        DateTime startTime, endTime;

        private void timer1_Tick_1(object sender, EventArgs e)
        {
            if (DateTime.Now.ToString() == endTime.ToString())
            {
                timer1.Stop();
                MessageBox.Show("開始時間:" + startTime + "\n現在時間:" + endTime.ToString() + "\n該關機了");
            }           
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            startTime = DateTime.Now;
            endTime = startTime.AddMinutes(55);//電腦打算用多久,請以分鐘為單位(預設55分鐘)
        }
    }
}

ps.需配合windows的自動排程在一開機的時候啟用,未來打算改成在背景執行作業

2011年7月26日 星期二

014-取得電腦本機IP

using System.Net;

 

System.Net.IPHostEntry IPHost = System.Net.Dns.GetHostEntry(Environment.MachineName);
if (IPHost.AddressList.Length > 0)
{
    MessageBox.Show(IPHost.AddressList[0].ToString(), "電腦本機IP");
}

2011年7月22日 星期五

013-簡易郵件寄送&一次寄信給兩個以上E-mail

using System.Net.Mail;

        public void send_email(string msg, string mysubject, string address)
        {
            MailMessage message = new MailMessage("ahhsu@blogspot.com", address);//MailMessage(寄信者, 收信者)
            message.IsBodyHtml = true;
            message.BodyEncoding = System.Text.Encoding.UTF8;//E-mail編碼
            message.Subject = mysubject;//E-mail主旨
            message.Body = msg;//E-mail內容

            message.Headers.Add("X-MSMail-Priority","High");//重要信標示
            message.Headers.Add("X-Priority", "1");//重要信標示


            SmtpClient smtpClient = new SmtpClient("192.168.1.XX", 25);//設定E-mail Server和port
            smtpClient.Send(message);
        }

send_email("測試內容", "測試主旨標題", "ahhsu@blogspot.com");//呼叫send_email函式測試
send_email("測試內容", "測試主旨標題", "ahhsu@blogspot.com,andy@good.com");//也可一次寄給多人

2011年7月21日 星期四

012-利用Gmail 寄信

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;

 

SmtpClient MySmtp = new SmtpClient("smtp.gmail.com",587);
MySmtp.UseDefaultCredentials = false;
MySmtp.Credentials = new NetworkCredential("帳號@gmail.com", "密碼");//設定帳號密碼
MySmtp.EnableSsl = true; //smtp 是否使用 SSL
MailMessage mms = new MailMessage();
mms.IsBodyHtml = false;//內容是不是HTML
mms.From = new MailAddress("帳號@gmail.com", "Gmail寄test", Encoding.UTF8);
mms.Sender = new MailAddress("帳號@gmail.com", "Gmail寄test", Encoding.UTF8);
mms.Subject = "C# Mail Test";//標題
mms.SubjectEncoding = Encoding.UTF8;
mms.To.Add(new MailAddress("andy@xx.COM.TW", "test", Encoding.UTF8));//收件者
mms.Body = "測試"; //內容
MySmtp.Send(mms);

2011年7月19日 星期二

011-常用正規表式

使用者名

/^[a-z0-9_-]{3,16}$/

密碼

/^[a-z0-9_-]{6,18}$/

十六進制值

/^#?([a-f0-9]{6}|[a-f0-9]{3})$/

電子郵箱

/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/

URL

/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/

IP 位址

/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/

HTML 標籤

/^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/

Unicode編碼中的漢字範圍

/^[\u2E80-\u9FFF]+$/