header image

C# WinForm Note

HOW TO OPEN WEBSITES FROM WIN FROM:
System.Diagnostics.Process.Start(“http://www.webpage.com”);
====================================================
GET FILES FROM CERTAIN FOLDER:
List myList = new List();

foreach (string fname in Directory.GetFiles(fb.SelectedPath))
{
StreamReader file = new System.IO.StreamReader(fname);
while ((line = file.ReadLine()) != null)
{
myList.Add(line.Trim());
}

file.Close();
}
====================================================
GET FILE NAME:
string filename = @”C:\test.txt”;

if (File.Exists(filename)) {
MessageBox.Show(“取得檔名(不包含附檔名)” + Path.GetFileNameWithoutExtension(filename));
MessageBox.Show(“取得副檔名:” + Path.GetExtension(filename));
MessageBox.Show(“資料根目錄:” + Path.GetPathRoot(filename));
MessageBox.Show(“取得路徑:” + Path.GetFullPath(filename));
}
====================================================
OUTPUT FILE IN UTF8:
StreamWriter SW = new StreamWriter(filePath, true, Encoding.UTF8, 1024);
====================================================
MAKE SCROLL BAR STAY AT BOTTOM:
myrichTextBox.SelectionStart = myrichTextBox.Text.Length; //Set the current caret position at the end
myrichTextBox.ScrollToCaret(); //Now scroll it automatically
====================================================
READ ALL FILES FROM CERTAIN DOCUMENT:
List myList = new List();

// 執行檔路徑下的 MyDir 資料夾
string folderName = System.Windows.Forms.Application.StartupPath + @”\MyDir”;

// 取得資料夾內所有檔案
foreach (string fname in System.IO.Directory.GetFiles(folderName))
{
string line;

// 一次讀取一行
System.IO.StreamReader file = new System.IO.StreamReader(fname);
while ((line = file.ReadLine()) != null)
{
myList.Add(line.Trim());
}

file.Close();
}
====================================================
POINT OF USING STREAM READER:
StreamReader sr = new StreamReader(openFileDialog1.FileName, Encoding.Default);
while (sr.Peek() != -1)
{}
====================================================
THE USE OF STRING.INDEXOF:

string a = “good day commander!”;
int i = a.IndexOf(“soldier”);
//while the sentence is without the word, the result comes to -1…
int j = a.IndexOf(“day”);
//it the case that the sentence contains such word, it will reply the index of the word…
Console.WriteLine(“YO!”);
Console.WriteLine(“i = ” + i);
Console.WriteLine(“j = ” + j);
Console.ReadLine(); //THE WAY TO CHECK THE READLINES…

Result>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
YO!
i = -1
j = 5
====================================================
THE WAY TO READ ALL FIELDS IN SQLDATAREADER:
while (DR.Read())
{
for (int i = 0; i < DR.FieldCount; i++)
{
Log[i] = DR[i].ToString();
}
}
====================================================
TO CREATE A PATH THAT DOESN'T EXIST:

if (!Directory.Exists(UserPath))
{
Directory.CreateDirectory(UserPath);
}

if (File.Exists(UserPath + "linkinfo.txt"))
{
StreamReader SRLog = new StreamReader(UserPath + "linkinfo.txt");
strServer = SRLog.ReadLine();
strDB = SRLog.ReadLine();
strID = SRLog.ReadLine();
strPW = SRLog.ReadLine();

Server_Log.Text = strServer;
DB_Log.Text = strDB;
ID_Log.Text = strID;
PW_Log.Text = strPW;

SRLog.Close();
cnstring = @"Server = " + strServer + @";database = " + strDB + @"; uid = " + strID + @"; pwd = " + strPW;
}
====================================================
HOW TO SPLIT A STRING INTO ARRAY:
string[] Token = { "**,**" };
string[] MailArray = MailStr.Split(Token, StringSplitOptions.None);
====================================================
Get GET Query String from web:
string Target = Request.QueryString["cmd"].ToString();
====================================================
Get information form internet:
private string getHtml(string URL)
{
WebClient myWebClient = new WebClient();
try
{
byte[] myDataBuffer = myWebClient.DownloadData(URL);

return Encoding.UTF8.GetString(myDataBuffer);
}
catch (Exception ex)
{
return "getHtml error " + ex.ToString();
}
}
====================================================
SELECT ALL TEXT WITH CTRL + A:
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.A)
{
((TextBox)sender).SelectAll();
}
====================================================
READ TEXT IN TEXTBOX:
string strLineData;
using (StringReader sr = new StringReader(textbox1.text.Trim()))
{
//讀取第一行
strLineData = sr.ReadLine();

while (!String.IsNullOrEmpty(strLineData))
{
//這邊放你的程式邏輯
//…

//讀取下一行
strLineData = sr.ReadLine();
}
}

====================================================
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public User GetOneUserInfo(string name, int age)
{
return (new User { Name = name, Age = age });

}
====================================================
SqlDataReader.IsDBNull 方法 :
while (reader.Read()) {
Console.Write(reader.GetString(reader.GetOrdinal("FirstName")));
// display middle name only of not null
if (!reader.IsDBNull(reader.GetOrdinal("MiddleName")))
Console.Write(" {0}", reader.GetString(reader.GetOrdinal("MiddleName")));
Console.WriteLine(" {0}", reader.GetString(reader.GetOrdinal("LastName")));
}
====================================================
焦點鎖定/預設關注:
this.ActiveControl = btn01;
====================================================
IP取得:
string tClientIP = Request.ServerVariables["REMOTE_ADDR"].ToString();
====================================================
轉址:Response.Redirect("http://e-road.pthg.gov.tw/html/edit_user_login.asp");
====================================================
Cookie生成
HttpCookie cookie = new HttpCookie("UtSystemCookie");//Cookie的名稱
DateTime dt = DateTime.Now;//獲取當前時間
TimeSpan ts = new TimeSpan(1, 0, 0, 0);//cookie有效作用時間,具體請參照查msdn
cookie.Expires = dt.Add(ts);//加入作用時間
cookie.Values.Add("Cate", detail.CategoryID.ToString());
cookie.Values.Add("Role", detail.RoleID.ToString());
Response.Cookies.Add(cookie);
===============================================
Request.Cookies["uster_net"]["emp_login"]