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

2017年4月26日 星期三

取得Client IP

P.S 僅Framkwork 3.5以上有效
string sHostName = System.Net.Dns.GetHostName();
string IP = Dns.GetHostEntry(sHostName).AddressList.First(o => o.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString();

2016年7月1日 星期五

字串應用

1.有小數點的數字字串,四捨五入取整數且加千分位
ex:string gg1 = 123456.78

decimal dgg = Convert.ToDecimal(gg1);
sting gg2 = dgg.ToString("#,#");
結果: 123,457

2016年5月19日 星期四

DataGridView塞入CheckBox、Button,Insert CheckBox、Button into DataGridView

1.塞入CheckBox:
  1.1 在Form_Load裡面:
            int iColumnCount = dataGridView1.ColumnCount;
            if (iColumnCount == 0)
            {
                DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn()
                {
                    Name = "選擇",
                    FalseValue = 0,
                    TrueValue = 1,
                    Visible = true
                };
                dataGridView1.Columns.Add(col);
            }
 
 1.2 檢視有被勾選的項目:
 foreach (DataGridViewRow row in dataGridView1.Rows)
 {
      DataGridViewCheckBoxCell chk = row.Cells[0] as DataGridViewCheckBoxCell;
      if(Convert.ToBoolean(chk.Value))
      {
          string data= row.Cells[1].Value.ToString() ;//取出第1欄位資料
      }
 }

2.塞入Button:
  2.1  在Form_Load裡面:
            int iColumnCount = dataGridView1.ColumnCount;
            if (iColumnCount == 0)
            {
                DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
                dataGridView1.Columns.Add(btn);
                btn.Name = "btn";
                btn.HeaderText = "標題";
                btn.Text = "執行";
                btn.UseColumnTextForButtonValue = true;
            }
  2.2 執行被按下的Button:
        在dataGridView1_CellClick裡面,
         if (e.ColumnIndex == 0)
         {
              ... do something...
              .
           }

2016年1月8日 星期五

開啟新的Form且定時自動關閉

1.Create new Form, name Form2
2.At Form1:
private void btn_Buttin1_Click(object sender, EventArgs e)
{
    Form2 FM2 = new Form2();
    FM2.ShowDialog();
}
3.At Form2:
private void Form2_Shown(object sender, EventArgs e)
{
    this.timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    this.timer1.Interval = 1000; //1秒
    this.Close();
}

2015年3月5日 星期四

將一專案副製成另一新的專案


1.複製專案的目錄成為另一目錄
2.用記事本編輯專案檔,譬如 project.sln,找到Project段落中的資了夾名稱改為新的名稱
3.開啟新專案後,右上角的方案總管,專案名稱改為新名稱

2015年2月24日 星期二

在AD環境,取得登入者的AD帳號

1.using System.DirectoryServices.AccountManagement;
2.var Name1 = UserPrincipal.Current;
   var Name2 = vADName.Surname;
   string UserName = Name2;

2014年11月24日 星期一

DataGridView增加欄位

DataGridViewTextBoxColumn col5 = new DataGridViewTextBoxColumn();
dataGridView1.Columns.Add(col5);
dataGridView1.Columns[5].Name = "Column5";
DataGridViewTextBoxColumn col6 = new DataGridViewTextBoxColumn();
dataGridView1.Columns.Add(col6);
dataGridView1.Columns[6].Name = "Column6";

2014年11月5日 星期三

用foreach逐行讀取DataGridView資料


foreach (DataGridViewRow row in dataGridView1.Rows)
{
     string Column1 = row.Cells[0].Value.ToString();
     string Column2 = row.Cells[1].Value.ToString();
}

2014年7月28日 星期一

調整2維陣列的長度

private static T[,] ResizeArray<T>(T[,] original, int rows, int cols)
        {
            var newArray = new T[rows, cols];
            int minRows = Math.Min(rows, original.GetLength(0));
            int minCols = Math.Min(cols, original.GetLength(1));
            for (int i = 0; i < minRows; i++)
                for (int j = 0; j < minCols; j++)
                    newArray[i, j] = original[i, j];
            return newArray;
        }

2014年3月25日 星期二

讀取TXT,內容寫到DataGridView



1.文字檔內容(以逗號將每欄位隔開):
SRV1,192.168.100.1,C:\,100,200
SRV2,192.168.100.2,C:\,100,200
SRV3,192.168.100.3,C:\,100,200

2.程式碼
private void Form1_Load(object sender, EventArgs e)
{
    TextReader txtReader = new StreamReader(@".\DiskInfo.txt");
    while (txtReader.Peek() != -1)
    {
        string[] parts = txtReader.ReadLine().Split(',');
        dataGridView1.Rows.Add(parts);
     }
 txtReader.Close();
}




2014年2月24日 星期一

將檔案或目錄壓縮成ZIP檔;ZIP File or Directory


1.下載 IONIC.ZIP.DLL 後加入到參考
2.using Ionic.Zip;
3.用法:
 private void button1_Click(object sender, EventArgs e)
{
    using (ZipFile zip = new ZipFile(Encoding.Default)) //Encoding.Default 處理中文問題
    {
        string FileName = "file.txt";
       
        //直接加縮
        zip.AddFile(FileName);
     
        //加密碼
        zip.Password = "password";
       
        //存檔
        zip.Save@("C:\")

        //整個目錄壓縮
        string sPathTo = @"C:\Temop";
        zip.AddDirectory(sPathTo);
        zip.Save@("C:\zipfile.zip")
    }
}


2013年12月27日 星期五

Excel相關應用

常常需要透過程式與Excel檔案做一些互動,用久了不外乎就是那幾種應用,這邊做個歸納供需要的時候取用。

一、產生新的Excel檔案
    1.先確定方案總管的參考裡面有Microsoft.Office.Interop.Excel 如果沒有請自行安裝。
    2.using Microsoft.Office.Interop.Excel;
    3.
    //建立Excel物件
    Microsoft.Office.Interop.Excel.Application xlapp =                     
    new Microsoft.Office.Interop.Excel.Application();
    
    //顯式檔案
    xlapp.Visible = true;
    
    //建立WorkBook物件
    Workbook wb = xlapp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            
    //建立WorkSheet物件
    Worksheet ws = (Worksheet)wb.Sheets[1];

    //指定要控制的藍為範圍
    Range rg = ws.get_Range("A:K", System.Type.Missing);
    
    //字型大小
    rg.Font.Size = 10;

    //字型粗體
    rg.Font.Bold = true;

    //儲存格設為純文字
    rg.NumberFormatLocal = "@";

    //背景顏色    
    rg.Cells.Interior.Color = ColorTranslator.ToOle(Color.FromArgb(255,255,0));
    
二、讀取現有的Excel檔案
 
    //宣告路徑字串
    string sFileWithPath = null;

    //宣告開檔對話框的物件  
    OpenFileDialog OFDialog1 = new OpenFileDialog();
 
    //指定預設開己的路徑為桌面
    OFDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
         
    //預設顯式Excel檔案
    OFDialog1.Filter = "*.xlsx|*.XLSX|*.xls|*.XLS";

    if (OFDialog1.ShowDialog() == DialogResult.OK)
    {
        sFileWithPath = OFDialog1.FileName;
        xlapp.Visible = true;
        Workbook wb = xlapp.Workbooks.Open(sFileWithPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        Worksheet ws = (Worksheet)wb.Sheets[1];     //指定第1個Sheet

        Range rg = ws.get_Range("L:X", System.Type.Missing);    //設定要控制的欄位區間
    .......
    ....
    }

三、金額處理
 若有一金額為99,999,用字串時需要千分位符號,計算時需拿掉。
   String to Double:
      string sMoney = "99,9999";
      double dMoneyCount = Convert.ToDouble(sMoney.Replace(",",""));
  Double to String:
      double dMoneyCount = 999999.0;
      string sMoney = dMoneyCount.ToString("#,##");


















2013年11月22日 星期五

將PDF檔加密碼 Encrypt PDF File

1.download iTextSharp.dll,Please find it by yourself

At VS2012 or other version:
2.import iTextSharp to reference
3.using System.IO;
   using iTextSharp.text;
   using iTextSharp.text.pdf;
4.At Button Event:
 private void button1_Click(object sender, EventArgs e)
        {
            Stream myStream = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "pdf files (*.pdf)|*.pdf|All files (*.*)|*.*";
            //openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    string filename = Path.GetFileName(openFileDialog1.FileName);
                   
                    if ((myStream = openFileDialog1.OpenFile()) != null)
                    {
                        textBox1.Text = filename;

                        string WorkingFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                        string InputFile = Path.Combine(WorkingFolder, "xx.pdf");
                        string OutputFile = Path.Combine(WorkingFolder, "xx_enc.pdf");

                        using (Stream input = new FileStream(InputFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            using (Stream output = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
                            {
                                PdfReader reader = new PdfReader(input);
                                PdfEncryptor.Encrypt(reader, output, true, "secret", "secret", PdfWriter.ALLOW_SCREENREADERS);
                               
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

2013年11月14日 星期四

Download file from FTP Server

    try
            {
                string FileNameToDownload = "filename.txt";  //檔名
                string DownloadFilePath = @"D://";  //存檔路徑
                FileStream outputStream = new FileStream(DownloadFilePath + "\\" + FileNameToDownload, FileMode.Create);

                string FTPip = "192.168.100.100"; //FTP Server IP
                FtpWebRequest repFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://"+FTPip+"/path/"+FileNameToDownload));
                repFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                repFTP.UseBinary = true;
                repFTP.Proxy = null;
                string ftpUserID = "user";
                string ftpPassword = "password";
                repFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

                FtpWebResponse response = (FtpWebResponse)repFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int buffersize = 2048;
                int readCount;
                byte[] buffer = new byte[buffersize];

                readCount = ftpStream.Read(buffer, 0, buffersize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, buffersize);
                }
                ftpStream.Close();
                outputStream.Close();
                response.Close();
                MessageBox.Show("Complete!");
            }
            catch (WebException ex)
            {
                String status = ((FtpWebResponse)ex.Response).StatusDescription;
                MessageBox.Show(status);
            }

2013年8月8日 星期四

Which RadioButton selected inside GroupBox or Panel

foreach (RadioButton rb in groupBox5.Controls.OfType<RadioButton>())
{
    if(rb.Checked)
        MessageBox.Show(rb.text);
}

在Windows Form上面放一個Table,動態產生XY軸及控制項

我不會將Code鉅細靡遺通通放上來,基本操作是programer的基本功,應該自己想辦法弄懂。

1.依指定的XY數量產生表格:先放一個TableLayoutPanel元件,建立一個Function:

//定益表格參數
int y = 3;
int x = 2;          
tableLayoutPanel1.Visible = false;
tableLayoutPanel1.BackColor = Color.FromArgb(192, 255, 192);
tableLayoutPanel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
tableLayoutPanel1.Controls.Clear();
tableLayoutPanel1.ColumnStyles.Clear();
tableLayoutPanel1.RowStyles.Clear();
tableLayoutPanel1.Refresh();
tableLayoutPanel1.RowCount = y;
tableLayoutPanel1.ColumnCount = x;

for (int co = 0; co < x; co++)
{
    ColumnStyle cs = new ColumnStyle(SizeType.Percent, 100 / x);
    tableLayoutPanel1.ColumnStyles.Add(cs);
}

for (int ro = 0; ro < y; ro++)
{
    RowStyle rs = new RowStyle(SizeType.Percent, 100 / y);
    tableLayoutPanel1.RowStyles.Add(rs);
}

2.以下範例,可在產生表格後、分別產生第一列及第一欄的Label
             //產生第一欄Label
             for (int co = 0; co < x; co++)
            {
                ColumnStyle cs = new ColumnStyle(SizeType.Percent, 100 / x);
                tableLayoutPanel4.ColumnStyles.Add(cs);

                if (co == 0)
                {
                    for (int r = 0; r < y; r++)
                    {
                        if (r != 0)
                        {
                            Label LblName;
                            LblName = new Label();
                            LblName.Dock = DockStyle.Fill;//填滿表格
                            LblName.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;//文字置中
                            LblName.BackColor = Color.FromArgb(255, 255, 192);//背景顏色
                            LblName.Font = new Font(LblName.Font, FontStyle.Bold);//粗體字
                            LblName.ForeColor = Color.Red;//字體紅色
                            if(x >=16)
                                LblName.Font = new Font("標楷體", 7);
                            LblName.Name = "R" + Convert.ToInt16(r);
                            LblName.Text = "R" + Convert.ToInt16(r);
                            tableLayoutPanel1.Controls.Add(LblName, 0, r);
                        }
                    }
                }
            }

            //產生第一列Label
            for (int ro = 0; ro < y; ro++)
            {
                RowStyle rs = new RowStyle(SizeType.Percent, 100 / y);
                tableLayoutPanel4.RowStyles.Add(rs);

                if (ro == 0)
                {
                    for (int c = 0; c < x;c++)
                    {
                        if (c != 0)
                        {
                            Label LblName;
                            LblName = new Label();
                            LblName.Dock = DockStyle.Fill;//填滿表格
                            LblName.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;//文字置中
                            LblName.BackColor = Color.FromArgb(255, 255, 192);//背景顏色
                            //LblName.Font = new Font(LblName.Font, FontStyle.Bold);//粗體字
                            LblName.ForeColor = Color.Red;//字體紅色
                            if (x >= 17)
                                LblName.Font = new Font("標楷體", 8);
                            if (x >= 20)
                                LblName.Font = new Font("標楷體", 7);
                            LblName.Name = "C" + Convert.ToInt16(c);
                            LblName.Text = "C" + Convert.ToInt16(c);
                            tableLayoutPanel1.Controls.Add(LblName, c, 0);
                        }
                    }
                }
            }

3.點選TableLayoutPanel時,動態產生Label:從TableLayoutPanel的MouseClick事件
                int row = 0;
                int verticalOffset = 0;
                tableLayoutPanel1.Visible = false;//產生Label的過程,畫面會跑來跑去,所以先隱藏掉
                foreach (int h in tableLayoutPanel1.GetRowHeights())
                {
                    int column = 0;
                    int horizontalOffset = 0;
                    foreach (int w in tableLayoutPanel1.GetColumnWidths())
                    {
                        Rectangle rectangle = new Rectangle(horizontalOffset, verticalOffset, w, h);
                        if (rectangle.Contains(e.Location))
                        {
                            //產生Label
                            Label LblName;
                            LblName = new Label();
                            LblName.Dock = DockStyle.Fill;//填滿表格
                            LblName.ForeColor = Color.Red;//字體紅色
                            LblName.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;//文字置中
                            LblName.Font = new Font(LblName.Font, FontStyle.Bold);//粗體字
                            LblName.Font = new Font("標楷體", 10);
                            LblName.Name = "A1";
                            LblName.Text = "A1";
                            tableLayoutPanel1.Controls.Add(LblName, column, row);
                           
                            LblName.Click += new System.EventHandler(LblName_Click);//動態事件
                            tableLayoutPanel4.Visible = true;
                            return;
                        }
                        horizontalOffset += w;
                        column++;
                    }
                    verticalOffset += h;
                    row++;

                }

4.宣告點擊動態產生的Label
 private void LblName_Click(object sender, System.EventArgs e)

 {
      dosomething;
 }

2013年6月25日 星期二

用System.DirectoryServices.AccountManagement管理AD帳號

http://www.codeproject.com/Articles/38344/Using-System-DirectoryServices-AccountManagement
根據已上網址資料,改以中文方式簡要說明:

1.System.DirectoryServices.AccountManagement 這是.NET Framework 3.5以後才有的,
.NET Framework 2.0 則是使用 DirectoryEntry,
2者相較,System.DirectoryServices.AccountManagement效能較佳。

2.相關物件說明:
PrincipalContext:與AD的連接物件
Principal:提供AD單元儲存、刪除、新增
GroupPrincipal:由Principal衍生而來,對Group單元做儲存、刪除、新增
UserPricipal:Principal衍生而來,對User單元做儲存、刪除、新增

3.程式範例:
新增帳號
using (var pc = new PrincipalContext(ContextType.Domain,"domain.com", "DC=domain,DC=com"))
{
    using (var up = new UserPrincipal(pc))
    {
        UserPrincipal usr = UserPrincipal.FindByIdentity(pc, "NewUser");
        if (usr != null)
        {
            MessageBox.Show("NewUser,此帳號已經存在!");
            return;
        }
        else
        {
            try
            {
                up.SamAccountName = textBox1.Text;
                up.SetPassword("P@ssw0rd");
                up.Enabled = true;
                //up.PasswordNeverExpires = true;//密碼永久有效
                up.ExpirePasswordNow();//下次登入時更改密碼
                up.Save();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fail!:" + ex);
                Application.Exit();
            }
        }
    }

}

將新增的帳號加入群組
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain.com", DC=com");
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx,"Domain Users");
if (grp != null)
{
    grp.Members.Add(ctx,IdentityType.Name,"NewUser");
    grp.Save();
    grp.Dispose();
}
ctx.Dispose();

2013年1月15日 星期二

動態的陣列長度

如果迴圈裡面一開始不確定陣列長度,可用此方法宣告:

string[] _array = new string[0];
<10 br="" i=""> Array.Resize(ref _array , _array .Length + 1); //調整陣列長度

2012年11月18日 星期日

GridView To PDF

嚴格的說,不是將GridView資料轉出到PDF,應該是說將網頁資料轉出到PDF,包含GridView,goole資料普遍都是利用免費的 iTextSharp Library達成目的,安裝方法不外乎就是下載dll檔,掛載到VS專案,程式表頭把相關參考加到Using。
使用過程遇到的案例參考:

1.這邊有詳細操作教學 http://danatang.blog.ntu.edu.tw/


2.中文問題,也可以參考 http://renjin.blogspot.tw/2009/01/using-chinese-fonts-in-itextsharp.html


2012年6月18日 星期一

建立一個可回傳字串陣列的Method


//=== 定義 ===
static string[] GetData(string sName)
        {
            SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=xx;Integrated Security=True");//HR
            conn.Open();
            string sDate = Convert.ToString(iDate); //日期
            string cmd = "select A,B FROM TABLE WHERE C = @para ";
         
            SqlCommand sqlcmd = new SqlCommand(cmd, conn);
            sqlcmd.Parameters.Add(new SqlParameter("@para", sName));

            SqlDataReader dr = sqlcmd.ExecuteReader();
            string[] ret = new string[2];
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    ret[0] = dr[0].ToString();
                    ret[1] = dr[1].ToString();
                 }
            }
            dr.Close();
            conn.Close();
            return ret;
        }

//=== 呼叫陣列 ===

string[] aGetList;
aGetList = GetData("Name");    //帶入帳號,for 回傳陣列資料