網路上搜尋來的email驗證,一直沒法完整擋掉有格式問題的郵件,所以只好自己上網練功,結果......研究老半天原來微軟有給範例= =",不過正規表示式 Regular Expression這個還是得要會一點,PO文繼續練功
http://msdn.microsoft.com/zh-tw/library/01escwtf.aspx
記得using System.Text.RegularExpressions;
網路上搜尋來的email驗證,一直沒法完整擋掉有格式問題的郵件,所以只好自己上網練功,結果......研究老半天原來微軟有給範例= =",不過正規表示式 Regular Expression這個還是得要會一點,PO文繼續練功
http://msdn.microsoft.com/zh-tw/library/01escwtf.aspx
記得using System.Text.RegularExpressions;
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,郵件主旨也不會有亂碼的出現。
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 { }
}
}
}
//數字字串不足,前面補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%
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());
}
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("已完成匯入...");
}
}
}
}
}
}
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;
}
}
}
編譯時出現System.Net.Dns.GetHostByName(string) 已過時
改成Dns.GetHostEntry(Dns.GetHostName());
/*************************************************************************
** 撰寫者:Andy(Andy) 撰寫日期:2011/08/19
** 用途: 1.
** 做法:
** 1.
** 注意事項:
** 1.
** 2.
** 維護記錄:
** 維護者:姓名(員工代號) 維護日期:日期
** 維護項目:
** 1.
** 2.
** 做法: 1.
** 2.
** 注意事項:
** 1.
*************************************************************************/
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的自動排程在一開機的時候啟用,未來打算改成在背景執行作業
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");
}
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");//也可一次寄給多人
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);
/^[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]+$/