Tumgik
#InitialDirectory
guangyaw · 2 years
Text
C# 使用 OpenFileDialog 開啟檔案
C# 使用 OpenFileDialog 開啟檔案
學習程式語言最重要的就是實踐, 只要實際操作演練過需要的功能, 就能夠從中學到經驗, 上次的 C# 教學介紹了使用主要 Interop 元件存取Excel 檔案, 今天則是要來介紹 C# 使用 OpenFileDialog 開啟檔案 其實微軟官方網站說明文件都寫得相當的詳細, 不愧為長久以來的軟體巨擘, 對於今天的 OpenFileDialog 當然也有詳細的說明與範例, 有興趣的人可以自行前往下載研究 要使用 OpenFileDialog 要先引入命名空間, 在 C# 程式中寫做: using System.Windows.Forms; 這樣就能夠使用 OpenFileDialog這個類別的各種屬性與方法, 當然詳細的資訊在官方網站都有說明, 此處範例程式僅以當下的使用情境呼叫相應的屬性與方法 Multiselect ,以布林值表示 ( true 或者…
Tumblr media
View On WordPress
0 notes
gpu-returns · 7 years
Text
時間はなくとも”エディタ”は作る。
さぁ、記事を書いていこう。
3年の「のづ」です。少し前に久しくアーケードの音ゲーをやったのだが、気付いたことがあった。
(……あれ?目と体が追いつかない!?)
ずいぶんと下手になってる…。
あと自分のやり方が雑になっていて、やっていた頃の俺はどうやっていたんだろうと聞きたいところだ。
それと、いつもゲームをやりながら考えている。
音ゲーって譜面データたくさんあるよなー。と。
一つの曲に難易度が3つか4つある。
例えば
難易度が「easy」、「normal」、[hard]の3つがあるとする。
譜面のデータには0から9までの1桁の数字が入るとすると
Tumblr media
こんな感じのデータをプログラマが決めた法則に基づいた文字の並びでテキストファイルもしくはバイナリファイルとしておいておき、ゲーム画面で読み込む。
のような流れになる。
ここで考えることがある。
・譜面のデータを変える時はどうするか
・法則の知らない人(作った人以外)がそのデータを変更したりするのか
昔の俺はこう考えた。
1つ目に関しては、わかるなら、そのデータを開き、書き換えることができるなら、書き換えればいい。
2つ目は、決めた法則を変更する人に教えて、できるようにすればいい。
昔の俺「よし、これで問題はなくなった!!」
今の俺「………まてまて!!問題は解決していないぞ!!!」
この方法でいざ作っていくと、easyの3つ目は5から8に変更するから、初めの文字からいち、にい、さん、ここを書き換える、と。
次はhardの34こ目を9から3にするから、えーと、どこが34こ目なんだ?
さらに0から9までならまだしも、アルファベットも変更するものだったりするならもう訳が分からない。このままいくと、難易度が3つある1つの曲を作るのにどれだけの時間がかかるのだろうか。
さらに言うと、一つの曲では、作ったゲームもその曲を聴くだけの音楽プレイヤーと化してしまうので、振り返ると、意外と無駄な時間を使っていたんだと感じる。
で、だ。
この膨大にかかりそうな時間を減らそうではないか。
そう、エディタ(ツールとも言える)で!
あ、ようやく本題です。
今年の1月ごろに作ったゲームで、
ブロックの上を走り続けてジャンプしながらゴールに進むゲーム作ったんだけど。
Tumblr media
これね、1ステージがそんなに長くないから、たくさんのステージが必要だったんだよね。
さっきの音ゲーの話にすると、緑のブロックが「N」で黄色のギザギザブロックが「#」みたいな感じで、
Tumblr media
こんな感じで作ってた。
一行目のはレベルとか全体の幅と高さとか基本情報のデータが入ってる。
(これを制作した後に知ったがtxtファイルは扱いづらいらしい)
これを書き換えて行くとステージも変わるんだけど、見てて本当の画面にNとかTとかでないからわかりにくい。
それがこうなるとどうなる?
Tumblr media
なんかゲームの画面に近くなった。
Tumblr media
マウスの操作でステージが作れる。
これだけでもだいぶ楽になり、作業効率もよくなる。
このエディタは、VisualStudioのC#言語で使える、Windowsフォームアプリケーションで作ったのだが、基本さえ押さえておけばすぐに作れる。
VisualStudioから新しいプロジェクトを開いてC#のWindowsフォームアプリケーションを開くとこんな感じの画面が出てくる
Tumblr media
この中央の小さなウィンドウが今回のエディタの画面になる。
左側にある、ツールボックスから、いろいろなものをこのウィンドウにつけることができる。
画面の大きさを変えて、テキストを入力するところを置いて、ボタンを置いて…
Tumblr media
うん、いい感じ。
追加したのは
「TextBox」が1つ、「Button」が2つ、
そしてデータの読み込みを行う「OpenFileDialog」と「SaveFileDialog」のみ。
ここからがコーディング。
読み込むボタンをダブルクリックすると、クリックしたときに処理されるメソッドが作られるので、そこに処理を書く。
保存するボタンも同様に書いていく。
using System; //テキスト読み込みに使う using System.IO; //プロジェクト>参照の追加>アセンブリ>フレームワーク>Microsoft.VisualBasicをチェックで使用可能 using Microsoft.VisualBasic.FileIO;namespace test {    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void 読み込むボタン_Click(object sender, EventArgs e)        {            openFileDialog1.FileName = "ChoseFile";            openFileDialog1.InitialDirectory = "C:\\"; ;            openFileDialog1.Filter = "バイナリファイル(*.bin)|*.bin|テキストファイル(*.txt)|*.txt|すべてのファイル(*.*)|*.*";            openFileDialog1.FilterIndex = 2;            openFileDialog1.Title = "開くファイルを選択してください";            if (openFileDialog1.ShowDialog() == DialogResult.OK)            {                TextFieldParser tf = new TextFieldParser(openFileDialog1.FileName, System.Text.Encoding.GetEncoding("shift_jis"));                tf.TextFieldType = FieldType.Delimited;                //データの読み込み                string loadText = tf.ReadToEnd();                tf.Close();                //読み込んだデータをほしい場所に入れてあげる。                textBox1.Text = loadText;            }        }        private void 保存するボタン_Click(object sender, EventArgs e)        {            saveFileDialog1.Filter =                    "バイナリファイル(*.bin)|*.bin|すべてのファイル(*.*)|*.*";            saveFileDialog1.FilterIndex = 0;            saveFileDialog1.Title = "保存先のファイルを選択してください";            if (saveFileDialog1.ShowDialog() == DialogResult.OK)            {                StreamWriter sw;                //Excelで開けるようシフトJISで保存                sw = new StreamWriter(saveFileDialog1.FileName, false, System.Text.Encoding.GetEncoding("shift_jis"));            sw.Write(textBox1.Text);             sw.Close();            }        }    } }
こうして、ここにテキストを入れてください。と書かれたところを保存することができる。
簡易的にコマンドを保存するエディターだとするとこうなる。
Tumblr media
あとは、ゲームに必要な物を盛り込ん���いって、よりよいものにしていくとよい。
画像を描画したり、モード変更のボタンを用意したり……
必要性について
エディタがあるといいことは
・時間の短縮になる
・直接値を変えることがないのでゲームで読み込むときに読み込みエラーを起こさなくなる。
だと思う。
ただ、さっきからエディタエディタと言っているが、悪く言うと、本来のゲームには出てくることのないものである。
なら、なぜ必要か?
それは時間短縮がされ、作業効率が良くなる。という部分が大きい。
(個人的に直接データの値を書き換えているとイライラする)
作り方によっては、1時間で1つのマップを作るより、10分で2つ作れるといったものもできる。
そのようなことを実現させるなら、ある程度ゲームができてきたときに、一息、エディタを作ってみてはどうだろうか。
1 note · View note
Text
note C#
https://www.facebook.com/howkteam/posts/884434491704278?hc_location=ufi //write mode keep old data using (StreamWriter writetext = new StreamWriter(pathFileBackUp,true)) { String dataline = ""; for (int i = 0; i < listViewKetQua.Items.Count; i++) { //MessageBox.Show(i.ToString()); dataline = listViewKetQua.Items[i].Text; try { dataline += "|" + listViewKetQua.Items[i].SubItems[1].Text; dataline += "|" + listViewKetQua.Items[i].SubItems[2].Text; dataline += "|" + listViewKetQua.Items[i].SubItems[3].Text; dataline += "|" + listViewKetQua.Items[i].SubItems[4].Text; dataline += "|" + listViewKetQua.Items[i].SubItems[5].Text; dataline += "|" + listViewKetQua.Items[i].SubItems[6].Text; dataline += "|" + listViewKetQua.Items[i].SubItems[7].Text; } catch { } } writetext.WriteLine(dataline); } // using (StreamWriter writetext = new StreamWriter("maSanPham.txt", true)) { writetext.WriteLine("maSanPham"+"\n"); } //get don gian async static void GetRequest2(string url) { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"); HttpResponseMessage response = await client.GetAsync(url); HttpContent content = response.Content; string mycontent = await content.ReadAsStringAsync(); System.IO.File.WriteAllText("writeText2.html", cc2); Console.WriteLine(mycontent); } //get khi co cookie var handler = new HttpClientHandler { UseCookies = false }; HttpClient client = new HttpClient(handler); client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"); //client.DefaultRequestHeaders.Add("Cookie", "sb=1586WS8Pg4fVLi-AVCTzZQfK; c_user=100006526419466; xs=5%3ANG6Ri7p3H8onDg%3A2%3A1497014231%3A9404%3A6163; fr=0FXEbpGWw32Iv0Syx.AWVnhAsyot5wHki6ksMTxdnoPEI.BZOp_W.EB.AAA.0.0.BZOp_X.AWUXzNlC; pl=n; lu=gA; "); client.DefaultRequestHeaders.TryAddWithoutValidation("Cookie", "sb=1586WS8Pg4fVLi-AVCTzZQfK; c_user=100006526419466; xs=5%3ANG6Ri7p3H8onDg%3A2%3A1497014231%3A9404%3A6163; fr=0FXEbpGWw32Iv0Syx.AWVnhAsyot5wHki6ksMTxdnoPEI.BZOp_W.EB.AAA.0.0.BZOp_X.AWUXzNlC; pl=n; lu=gA; "); HttpResponseMessage response = await client.GetAsync(url); HttpContent content = response.Content; string mycontent = await content.ReadAsStringAsync(); // HttpContent header= content.Headers(); //response.Headers; System.IO.File.WriteAllText(@"C:\Users\nghiahsgs\Desktop\WriteText3.html", mycontent); Console.WriteLine(mycontent); ;get token using (var client = new HttpClient()) { //client.BaseAddress=new Uri("https://api.facebook.com/restserver.php"); client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", agent); var response = client.GetAsync("https://api.facebook.com/restserver.php" + strquerystring).Result; //client.DefaultRequestHeaders. switch (response.StatusCode) { case HttpStatusCode.OK: dynamic result = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result); if (result.access_token != null) { live++; string dtCookie = ""; List<OutCookie> Cookies = JsonConvert.DeserializeObject<List<OutCookie>>(result.session_cookies.ToString()); foreach (var itemc in Cookies) { dtCookie += itemc.name + "=" + itemc.value + ";"; } results.Add(new Result { User = user, Pass = pass, Token = result.access_token, Cookie = dtCookie, State = "LIVE" }); } else { die++; results.Add(new Result { User = user, Pass = pass, Token = "", Cookie = "", State = "DIE" }); } break; default: die++; results.Add(new Result { User = user, Pass = pass, Token = "", Cookie = "", State = "DIE" }); break; } } //post don gian public static async Task<string> Upload(byte[] image) { using (var client = new HttpClient()) { using (var content = new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture))) { content.Add(new StreamContent(new MemoryStream(image)), "bilddatei", "upload.jpg"); using ( var message = await client.PostAsync("http://www.directupload.net/index.php?mode=upload", content)) { var input = await message.Content.ReadAsStringAsync(); return !string.IsNullOrWhiteSpace(input) ? Regex.Match(input, @"http://\w*\.directupload\.net/images/\d*/\w*\.[a-z]{3}").Value : null; } } } } //tach json using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; //JToken jtoken = o["paging"]["next"]; if(jtoken != null) { url = o["paging"]["next"].ToString(); } else { url = ""; } */ namespace jsonDecode { class Program { static void Main(string[] args) { string data = System.IO.File.ReadAllText(@"C:\Users\nghiahsgs\Desktop\chatFuelApi.txt"); //var data = c.DownloadString("http://localhost/json.php"); //Console.WriteLine(data); JObject o = JObject.Parse(data); for (int i=0;i< o["reactions"]["data"].Count();i++) { Console.WriteLine("id: " + o["reactions"]["data"][i]["id"]); } Console.ReadKey(); } } } // ghi ndung len file moi van giu ndung cu using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true)) { file.WriteLine("Fourth line"); } //api fb JObject o = JObject.Parse(cc); if (o["accounts"] != null) { if (o["accounts"]["data"] != null) { for (int i = 0; i < o["accounts"]["data"].Count(); i++) { //Console.WriteLine("id: " + o["reactions"]["data"][i]["id"]); //MessageBox.Show(o["accounts"]["data"][i]["id"].ToString()); if (richTextBoxListTokenPage.InvokeRequired) { richTextBoxListTokenPage.BeginInvoke(new MethodInvoker(delegate () { if (richTextBoxListTokenPage.Lines.Count() == 0) { richTextBoxListTokenPage.AppendText(o["accounts"]["data"][i]["name"].ToString() + "|" + o["accounts"]["data"][i]["id"].ToString() + "|" + o["accounts"]["data"][i]["access_token"].ToString()); } else { // richTextBoxListPageChangeAvatar.AppendText("\nnghiahsgs"); richTextBoxListTokenPage.AppendText("\n" + o["accounts"]["data"][i]["name"].ToString() + "|" + o["accounts"]["data"][i]["id"].ToString() + "|" + o["accounts"]["data"][i]["access_token"].ToString()); } })); } else { lock (richTextBoxListTokenPage) { if (richTextBoxListTokenPage.Lines.Count() == 0) { richTextBoxListTokenPage.AppendText(o["accounts"]["data"][i]["name"].ToString() + "|" + o["accounts"]["data"][i]["id"].ToString() + "|" + o["accounts"]["data"][i]["access_token"].ToString()); } else { // richTextBoxListPageChangeAvatar.AppendText("\nnghiahsgs"); richTextBoxListTokenPage.AppendText("\n" + o["accounts"]["data"][i]["name"].ToString() + "|" + o["accounts"]["data"][i]["id"].ToString() + "|" + o["accounts"]["data"][i]["access_token"].ToString()); } } } Thread.Sleep(10); } } else { } } //get id posts cua 1 id bat ky async static void GetRequest2() { HttpClient client = new HttpClient(); // url goc String urlGoc = "https://graph.facebook.com/LeThiHaiYenT60?fields=posts&access_token=EAAAAUaZA8jlABABOFezBiBZCgpYMP4chZBEiUEC5WbNo9F5IGEHeFndKKZAOZC6bWF2bcXvtsVpInskYZCJhOSng1I5e8pxmEbplQI7Rfd7DzM8a6kZBQDIcpFZBg8XK473ZCZCYfeZBK8hGI1ewPqSjJAWnDbxaTcaRcfIXZAwlgVWthAZDZD"; HttpResponseMessage responseGoc = await client.GetAsync(urlGoc); HttpContent contentGoc = responseGoc.Content; string mycontentGoc = await contentGoc.ReadAsStringAsync(); // System.IO.File.WriteAllText(@"C:\Users\nghiahsgs\Desktop\WriteText2.html", mycontent); //Console.WriteLine(mycontent); // return mycontent; JObject oGoc = JObject.Parse(mycontentGoc); for (int i = 0; i < oGoc["posts"]["data"].Count(); i++) { Console.WriteLine("id: " + oGoc["posts"]["data"][i]["id"]); } String url = oGoc["posts"]["paging"]["next"].ToString(); //String url = "https://graph.facebook.com/v1.0/100010543214477/posts?access_token=EAAAAUaZA8jlABABOFezBiBZCgpYMP4chZBEiUEC5WbNo9F5IGEHeFndKKZAOZC6bWF2bcXvtsVpInskYZCJhOSng1I5e8pxmEbplQI7Rfd7DzM8a6kZBQDIcpFZBg8XK473ZCZCYfeZBK8hGI1ewPqSjJAWnDbxaTcaRcfIXZAwlgVWthAZDZD&limit=25&until=1495541605&__paging_token=enc_AdAqolcbu4GGFDfkNWBbIi1oMAyWLL7BlKFLLeRbzxhzG1xK2oFVLA9jzSs0EVcJ9DBhlZARRW3ZARXtKwMKR7ETJO8FzVOKF9ovdHHWPByJQd9wZDZD"; //chui vao vong lap tim cac id cu for(int j=0;j<2;j++) //while (url != "") { //client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"); HttpResponseMessage response = await client.GetAsync(url); HttpContent content = response.Content; string mycontent = await content.ReadAsStringAsync(); // System.IO.File.WriteAllText(@"C:\Users\nghiahsgs\Desktop\WriteText2.html", mycontent); //Console.WriteLine(mycontent); // return mycontent; JObject o = JObject.Parse(mycontent); for (int i = 0; i < o["data"].Count(); i++) { Console.WriteLine("id: " + o["data"][i]["id"]); using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\nghiahsgs\Desktop\a.txt", true)) { file.WriteLine(o["data"][i]["id"]); file.Close(); } } url = o["paging"]["next"].ToString(); //Console.WriteLine(url); //Console.ReadKey(); } } //open file dialog OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = "c:\\"; openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { txtPathSave.Text = openFileDialog1.FileName; } //open folder dialog using (var fbd = new FolderBrowserDialog()) { DialogResult result = fbd.ShowDialog(); if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath)) { //string[] files = Directory.GetFiles(fbd.SelectedPath); ///System.Windows.Forms.MessageBox.Show("Files found: " + files.Length.ToString(), "Message"); /// //MessageBox.Show(fbd.SelectedPath); TxtStringFolder.Text = fbd.SelectedPath; } } //get all folder in folder var directories = Directory.GetDirectories(TxtStringFolder.Text); MessageBox.Show("nghiahsgs"); foreach (var directorie in directories) { //Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name); MessageBox.Show(directorie.ToString()); } //ket noi control thi bo static async void GetRequest2(object sender, EventArgs e, string idObject, string pathFileOutput, string token) //doc file using (StreamReader sr = new StreamReader("textfile.txt")) { string line; // doc va hien thi cac dong trong file cho toi // khi tien toi cuoi file. while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } //add ndung vao list view ListViewItem item = new ListViewItem(txtId.Text); item.SubItems.Add(txtName.Text); item.SubItems.Add(txtName2.Text); listView1.Items.Add(item); //sua noi dung listview listview.Items[iHang].SubItems[0].Text = ressult; //get item check chon checkbox cho listview //listView1.ItemChecked MessageBox.Show(listView1.Items[0].Checked.ToString()); MessageBox.Show(listView1.Items[0].Checked.ToString()); //lay ndung item string x=listView1.Items[0].Text; MessageBox.Show(x); // using System.Collections; class ListViewItemComparer : IComparer { private int col; private SortOrder order; public ListViewItemComparer() { col = 0; order = SortOrder.Ascending; } public ListViewItemComparer(int column, SortOrder order) { col = column; this.order = order; } public int Compare(object x, object y) { int returnVal; // Determine whether the type being compared is a date type. try { // Parse the two objects passed as a parameter as a DateTime. System.DateTime firstDate = DateTime.Parse(((ListViewItem)x).SubItems[col].Text); System.DateTime secondDate = DateTime.Parse(((ListViewItem)y).SubItems[col].Text); // Compare the two dates. returnVal = DateTime.Compare(firstDate, secondDate); } // If neither compared object has a valid date format, compare // as a string. catch { // Compare the two items as a string. returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text); } // Determine whether the sort order is descending. if (order == SortOrder.Descending) // Invert the value returned by String.Compare. returnVal *= -1; return returnVal; } } //ham sap xep listview : neu click vao cot khac thi no sap xep tang dan neu dung cot do thi giam dan.Chon su kien colum click private int sortColumn = -1; private void listView1_ColumnClick(object sender, ColumnClickEventArgs e) { // Determine whether the column is the same as the last column clicked. if (e.Column != sortColumn) { // Set the sort column to the new column. sortColumn = e.Column; // Set the sort order to ascending by default. listView1.Sorting = SortOrder.Ascending; } else { // Determine what the last sort order was and change it. if (listView1.Sorting == SortOrder.Ascending) listView1.Sorting = SortOrder.Descending; else listView1.Sorting = SortOrder.Ascending; } // Call the sort method to manually sort. listView1.Sort(); // Set the ListViewItemSorter property to a new ListViewItemComparer // object. this.listView1.ListViewItemSorter = new ListViewItemComparer(e.Column, listView1.Sorting); } //da luong C# https://www.youtube.com/watch?v=IJE-eYo983M new Thread(() =>{ }).Start(); c2: Thread th = new Thread(HamAdd); th.IsBackground = true; th.Start(); ;them vao InitializeComponent Control.CheckForIllegalCrossThreadCalls = false; //set time out cho luong var task = Task.Run(() => { try { GetBanDeXuatAndKetBan(nick, numberWantAdd, timeSleep2Fr, iHangListView, typeLogin); } catch { } }); if (task.Wait(TimeSpan.FromSeconds(MaxTimeWait))) { } else { } //da luong dat ten luong void A(string x, string y) { Thread.Sleep(3000); MessageBox.Show(x+y); } Thread ts1 = new Thread(() => { A("nghiahsgs", "nghiahsgs2"); }); ts1.Start(); ts1.Join(); MessageBox.Show("ok"); //check cross thread Thread t1; t1 = new Thread(Thread1); t1.Start(); t1.Join(); MessageBox.Show("ok"); private void Thread1() { String s = "nghiahsgs"; if (textBox1.InvokeRequired) { textBox1.BeginInvoke(new MethodInvoker(delegate () { textBox1.Text=s; })); } else { lock (textBox1) { textBox1.AppendText(s); textBox1.AppendText(Environment.NewLine); } } } +vs listview thi private void Thread1() { if (listViewThongTinCheck.InvokeRequired) { //MessageBox.Show("ok"); listViewThongTinCheck.BeginInvoke(new MethodInvoker(delegate () { // MessageBox.Show("ok"); ListViewItem item1 = new ListViewItem("nghiahsgs"); listViewThongTinCheck.Items.Add(item1); })); } } //da luong co tham so Thread t1 = new Thread(download); t1.Start("nghiahsgs"); t1.Join(); MessageBox.Show("ok"); public void download(object filename) { // download code MessageBox.Show(filename.ToString()); } //xoa item listview listView1.Items.Clear(); //luu all ndung listView1 for(int i = 0; i < listView1.Items.Count; i++) { string x = listView1.Items[0].Text; string y = listView1.Items[0].SubItems[1].Text; MessageBox.Show(x); MessageBox.Show(y); } //luu nhung ndung da cho listView1 int x=listView1.SelectedIndices.Count; MessageBox.Show(x.ToString()); for(int i=0;i< listView1.SelectedIndices.Count; i++) { MessageBox.Show(listView1.Items[listView1.SelectedIndices[i]].Text); } //xoa 1 line listView1 listView1.Items[i].Remove(); //loc trung listview private void button6_Click(object sender, EventArgs e) { for(int i = 0; i < listView1.Items.Count; i++) { //MessageBox.Show(i.ToString()); string ndungDongDo = listView1.Items[i].Text; for(int j = 0; j < i; j++) { // MessageBox.Show(j.ToString()); if (ndungDongDo == listView1.Items[j].Text) { listView1.Items[i].Remove(); i--; // break; } } } } //check tab select if(tabControl1.SelectedTab == tabControl1.TabPages[0]) { MessageBox.Show("hello form tab 0"); } //chuyen tab select tabControl1.SelectedTab = tabControl1.TabPages[1]; //input box add ref visualbasic using Microsoft.VisualBasic; Interaction.InputBox("Question?", "Title", "Default Text"); //luu file // MessageBox.Show("hello form tab 0"); SaveFileDialog savefile = new SaveFileDialog(); // set a default file name savefile.FileName = "uidbanBe.txt"; // set filters - this can be done in properties as well savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"; if (savefile.ShowDialog() == DialogResult.OK) { //using (StreamWriter sw = new StreamWriter(savefile.FileName)) // sw.WriteLine("Hello World!"); for (int i = 0; i < listView1.Items.Count; i++) { string x = listView1.Items[i].Text; string y = listView1.Items[i].SubItems[1].Text; string NdungLineSave = x + "|" + y; using (System.IO.StreamWriter file = new System.IO.StreamWriter(savefile.FileName, true)) { file.WriteLine(NdungLineSave); } } MessageBox.Show("đã lưu file thành công!"); } //them link cho picturebox pictureBox1.ImageLocation = "http://media.bongda.com.vn/files/anh.vu/2017/03/30/3a1-1010.jpg"; using System.Diagnostics; private void pictureBox1_Click(object sender, EventArgs e) { Process.Start("https://www.facebook.com/nghiahsgs"); } //regex String x = "5982149607"; Match y=Regex.Match(x, "[0-9]"); while (true) { Console.Write(y.ToString()); y = y.NextMatch(); } Console.Read(); //chi lay dung ket qua regex txtToken.Text = token.Groups[1].ToString(); //vd regex String x = "https://www.facebook.com/nghiahsgs/posts/2136461133248080?pnref=story"; Match y = Regex.Match(x, "[0-9]{16}"); MessageBox.Show("ok"); String kq = ""; while (y.ToString() != "") { kq = y.ToString(); y = y.NextMatch(); } MessageBox.Show(kq); //regex get all mail string x = "[email protected] [email protected] [email protected] dmasmdkad [email protected]"; Match y = Regex.Match(x, @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"); while (true) { MessageBox.Show(y.ToString()); y = y.NextMatch(); } //list trong C# List<string> termsList = new List<string>(); termsList.Add(texttxtMangACon.Groups[1].ToString()); //chuyen tu list to array string[] mangTest = termsList.ToArray(); //xnet C# HttpRequest request = new HttpRequest(); request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0"; request.Cookies = new CookieDictionary(); request.AddHeader("Accept", "text/html,application/xhtml+xml,application/xml"); request.AddHeader("Upgrade-Insecure-Requests", "1"); string cc = request.Get("https://www.reddit.com/").ToString(); File.WriteAllText("Regedit2.html", cc); Process.Start("Regedit2.html"); HttpRequest request = new HttpRequest(); request.UserAgent =Http.ChromeUserAgent(); request.Cookies = new CookieDictionary(); String cc = request.Get("https://graph.facebook.com/me?access_token=EAACW5Fg5N2IBAMR8ApK7FF5dfdaZCzq3yvpeJYDTmrErzJi5vCZA19XLiwYUVZAZAGlk4enuSsEGGkDSvnmbiXY8InkFlKYsWuZBQFQqOfmLkdCPWScl9nu6GOqUj4LKA4ciaTEyCjZBM9aHD3DUECs0yCxql9C6Hf2Lpm4HuxaHEdRjqMrBq8KJZCccQvkhFKjGUr1Qc2B5QZDZD").ToString(); phone = Uri.EscapeUriString(phone); data64= System.Uri.EscapeDataString(data64); //post string dataPost String url2 = "http://repib.nghiahsgs.com/api/insert.php"; HttpRequest request2 = new HttpRequest(); request2.UserAgent = Http.ChromeUserAgent(); request2.Cookies = new CookieDictionary(); request2.AddHeader("upgrade-insecure-requests", "1"); String cc2 = request2.Post(url2, dataPost, "application/x-www-form-urlencoded").ToString(); //import coookie //get location response http.Address.tostring //Chuyen Form C# if (txtUsername.Text == "nghiahsgs" && txtPassword.Text == "261997") { MessageBox.Show("Đăng nhập thành công"); this.Hide(); Form2 f2 = new Form2(); f2.ShowDialog(); this.Close(); } else { MessageBox.Show("sai pass"); } //Ket noi vs db mysql add ref la mysql.data.dll using MySql.Data.MySqlClient; try { string ConnectionString = "Server=localhost;Database=demo;Port=3306;User Id=root;Password="; MySqlConnection conn = new MySqlConnection(ConnectionString); conn.Open(); MessageBox.Show("thanh cong"); } catch { MessageBox.Show("thaat bai"); } //ket noi db va doc cac fields string ConnectionString = "Server=localhost;Database=demo;Port=3306;User Id=root;Password="; MySqlConnection conn = new MySqlConnection(ConnectionString); MySqlCommand cmd=conn.CreateCommand(); //read cmd.CommandText = "SELECT * FROM `bang`"; //insert cmd.CommandText = "INSERT INTO `bang`(`userName`, `passWord`, `age`) VALUES ('langoc','123','19')"; try { conn.Open(); //insert cmd.ExecuteNonQuery(); //read MySqlDataReader reader=cmd.ExecuteReader(); while (reader.Read()) { MessageBox.Show(reader["userName"].ToString()); } } catch { MessageBox.Show("loi"); } finally { conn.Close(); conn.Dispose(); //giai phong taif nguyen conn = null; } //export file excel //co replace add ref microsoft office interop excel dll SaveFileDialog savefile = new SaveFileDialog(); // set a default file name savefile.FileName = "uidbanBe.xls"; // set filters - this can be done in properties as well savefile.Filter = "Excel Workbook|*.xls"; if (savefile.ShowDialog() == DialogResult.OK) { MessageBox.Show("đã lưu file thành công!"); Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); Workbook wb = app.Workbooks.Add(XlSheetType.xlWorksheet); Worksheet ws = (Worksheet)app.ActiveSheet; app.Visible = false; ws.Cells[1, 1] = "nghiahsgs"; wb.SaveAs(savefile.FileName,XlFileFormat.xlWorkbookDefault,Type.Missing,Type.Missing,true,false,XlSaveAsAccessMode.xlNoChange,XlSaveConflictResolution.xlLocalSessionChanges,Type.Missing,Type.Missing); app.Quit(); MessageBox.Show("đã lưu file thành công!"); } //luu listview bang excel SaveFileDialog savefile = new SaveFileDialog(); // set a default file name savefile.FileName = "uidbanBe.xls"; // set filters - this can be done in properties as well savefile.Filter = "Excel Workbook|*.xls"; if (savefile.ShowDialog() == DialogResult.OK) { // MessageBox.Show("đã lưu file thành công!"); Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); Workbook wb = app.Workbooks.Add(XlSheetType.xlWorksheet); Worksheet ws = (Worksheet)app.ActiveSheet; app.Visible = false; //dien ten cac cot ws.Cells[1, 1] = "UID"; ws.Cells[1, 2] = "Tên"; ws.Cells[1, 3] = "Bạn bè"; ws.Cells[1, 4] = "Giới tính"; ws.Cells[1, 5] = "Birthday"; ws.Cells[1, 6] = "Location"; ws.Cells[1, 7] = "email"; ws.Cells[1, 8] = "Relationship"; ws.Cells[1, 9] = "Hometown"; ws.Cells[1, 10] = "Quotes"; for (int i = 0; i < listView1.Items.Count; i++) { // MessageBox.Show(listView1.Items[i].Text); ws.Cells[i + 2, 1] = listView1.Items[i].Text; ws.Cells[i + 2, 2] = listView1.Items[i].SubItems[1].Text; ws.Cells[i + 2, 3] = listView1.Items[i].SubItems[2].Text; ws.Cells[i + 2, 4] = listView1.Items[i].SubItems[3].Text; ws.Cells[i + 2, 5] = listView1.Items[i].SubItems[4].Text; ws.Cells[i + 2, 6] = listView1.Items[i].SubItems[5].Text; ws.Cells[i + 2, 7] = listView1.Items[i].SubItems[6].Text; ws.Cells[i + 2, 8] = listView1.Items[i].SubItems[7].Text; ws.Cells[i + 2, 9] = listView1.Items[i].SubItems[8].Text; ws.Cells[i + 2, 10] = listView1.Items[i].SubItems[9].Text; } wb.SaveAs(savefile.FileName, XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, true, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing); app.Quit(); MessageBox.Show("đã lưu file thành công!"); } //doc ma may //ket hop processorid + motherboard static void Main(string[] args) { GetNumberMachine("Win32_Processor", "ProcessorID"); //Then you can get the motherboard serial number: GetNumberMachine("Win32_BaseBoard", "SerialNumber"); Console.ReadKey(); } private static void GetNumberMachine(string hwClass,string syntax) { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM "+hwClass); foreach (ManagementObject queryObj in searcher.Get()) { Console.Write(queryObj[syntax]); } } //load anh pictureBox1 var request = WebRequest.Create("http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG"); using (var response = request.GetResponse()) using (var stream = response.GetResponseStream()) { pictureBox1.Image = Bitmap.FromStream(stream); } //php change picture from 1 url co dinh <?php $remoteImage = "http://media.thethaovanhoa.vn/Upload/1ULa3urWs9Lc3ZdKw10L3Q/files/2017/06/Mung%202/14792088093755.jpg"; $imginfo = getimagesize($remoteImage); header("Content-type: {$imginfo['mime']}"); readfile($remoteImage); ?> //create md5 public static string CreateMD5(string input) { // Use input string to calculate MD5 hash using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create()) { byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input); byte[] hashBytes = md5.ComputeHash(inputBytes); // Convert the byte array to hexadecimal string StringBuilder sb = new StringBuilder(); for (int i = 0; i < hashBytes.Length; i++) { sb.Append(hashBytes[i].ToString("X2")); } return sb.ToString(); } } //phantomjs in C# static void Main(string[] args) { String script = "console.log('nghiahsgs'); phantom.exit();"; string result=run_script(script); Console.WriteLine(result); Console.ReadLine(); } private static String run_script(String script) { String output = ""; var phantomjs = new PhantomJS(); phantomjs.OutputReceived += (sender, e) => { output += e.Data; }; phantomjs.RunScript(script,null); return output; } //phantomjs in cmd static void Main(string[] args) { String result= run_script("script.js"); Console.WriteLine(result); Console.ReadLine(); } private static String run_script(String script) { String cmd = (" " + script); System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = "phantomjs.exe"; proc.StartInfo.Arguments = cmd; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; //no mo cua so console khi chay winform proc.StartInfo.CreateNoWindow = true; proc.Start(); string output = proc.StandardOutput.ReadToEnd(); return output; } //chay phantom co tham so static void Main(string[] args) { Console.WriteLine("script.js \"http://phantomjs.org/\""); //run scrip la cau lenh giong nhu go tren cmd luc chay phamtomjs String result= run_script("script.js \"http://phantomjs.org/\""); Console.WriteLine(result); Console.ReadLine(); } ;ben file js se la var system=require('system'); var url = system.args[1]; //active tab tabcontrol tabControl1.SelectedTab = tabPage3; //fix cứng width and height cho form public Form1() { InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false; //pictureBox1.ImageLocation = "http://media.bongda.com.vn/files/anh.vu/2017/03/30/3a1-1010.jpg"; // pictureBox1.ImageLocation = "http://nghiahsgs1000.000webhostapp.com/bannerToolCuongBig.html"; // Define the border style of the form to a dialog box. this.FormBorderStyle = FormBorderStyle.FixedDialog; // Set the MaximizeBox to false to remove the maximize box. this.MaximizeBox = false; // Set the MinimizeBox to false to remove the minimize box. // this.MinimizeBox = false; // Set the start position of the form to the center of the screen. this.StartPosition = FormStartPosition.CenterScreen; // Display the form as a modal dialog box. //this.ShowDialog(); } //export data form listview to excel faster //using Excel = Microsoft.Office.Interop.Excel; String[,] myArr = new string[10, 10]; for (int x = 0; x < 10; x++) { for (int y = 0; y < 10; y++) { myArr[x, y] = "Test " + y.ToString() + x.ToString(); } } Excel.Application xlApp = new Excel.Application(); xlApp.Visible = true; Excel.Workbook wb = xlApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet); Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets.get_Item(1); Excel.Range rng = ws.Cells.get_Resize(myArr.GetLength(0), myArr.GetLength(1)); rng.Value2 = myArr; //dat ten va save Workbook luon wb.SaveAs(@"C:\Users\nghiahsgs\Desktop\test2.xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); wb.Close(); //export data form listview to excel ví dụ String[,] myArr = new string[listView1.Items.Count, 2]; for (int x = 0; x < listView1.Items.Count; x++) { for (int y = 0; y < 2; y++) { if (y == 0) { myArr[x, y] = listView1.Items[x].Text; } { myArr[x, y] = listView1.Items[x].SubItems[y].Text; } } } Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); xlApp.Visible = true; Microsoft.Office.Interop.Excel.Workbook wb = xlApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.get_Item(1); Microsoft.Office.Interop.Excel.Range rng = ws.Cells.get_Resize(myArr.GetLength(0), myArr.GetLength(1)); rng.Value2 = myArr; MessageBox.Show("Đã trích xuất dữ liệu xong."); //lap trinh bat dong bo async private async void Change2() { await Task.Factory.StartNew(() => { Thread.Sleep(5000); MessageBox.Show("ok"); }); } private void button1_Click(object sender, EventArgs e) { Change2(); } //bat dong bo c2 Task[] tasks = new Task[10]; for (int i = 0; i < 10; i++) { tasks[i] = Task.Factory.StartNew(() => DoSomeWork(10000000)); } Task.WaitAll(tasks); MessageBox.Show("xong 10 cai"); static void DoSomeWork(int val) { // Pretend to do something. Thread.Sleep(10000); MessageBox.Show("ok"); } //combo box add item comboBoxListPage.DisplayMember = "Text"; comboBoxListPage.ValueMember = "Value"; comboBoxListPage.Items.Add(new { Text = "report A", Value = "reportA" }); //chon item select combobox comboBoxListPage.SelectedIndex = 0; //doc value combox box MessageBox.Show(comboBoxListPage.Text‌​); MessageBox.Show((comboBoxListPage.SelectedItem as dynamic).Value); //add text to ricktextbox richTextBoxTokenPage.AppendText("\n\rnghiahsgs"); if (richTextBoxTokenPage.Lines.Count() == 0) { richTextBoxTokenPage.AppendText("nghiahsgs"); } else { richTextBoxTokenPage.AppendText("\nnghiahsgs"); } //line by line richtextbox for(int i=0;i< richTextBoxTokenPage.Lines.Count(); i++) { MessageBox.Show(richTextBoxTokenPage.Lines[i]); } //string split string[] tokens = stringX.Split('|'); MessageBox.Show(tokens[0]); MessageBox.Show(tokens[1]); //random Random rnd = new Random(); int month = rnd.Next(1, 13); // month: >= 1 and < 13 int dice = rnd.Next(1, 7); // dice: >= 1 and < 7 int card = rnd.Next(52); // card: >= 0 and < 52 //chrome selenium //allow accept alert driver.SwitchTo().Alert().Accept(); ChromeDriverService service = ChromeDriverService.CreateDefaultService(); service.HideCommandPromptWindow = true; var options = new ChromeOptions(); options.AddArgument("start-maximized"); //options.AddArgument("--window-position=-32000,-32000"); //options.AddArgument("--disable-notifications"); options.AddArgument("--headless"); //don't load image options.AddUserProfilePreference("profile.default_content_setting_values.images", 2); options.AddArgument("--user-agent=Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14"); var driver = new ChromeDriver(service, options); //checkbox checkBox1.Checked.ToString() //login fb selenium var driverService = PhantomJSDriverService.CreateDefaultService(); driverService.HideCommandPromptWindow = true; PhantomJSOptions options = new PhantomJSOptions(); options.AddAdditionalCapability("phantomjs.page.settings.userAgent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36"); var driver = new PhantomJSDriver(driverService, options); driver.Navigate().GoToUrl("https://www.facebook.com/login.php"); //Thread.Sleep(3000); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); IWebElement myDynamicElement = wait.Until<IWebElement>(d => d.FindElement(By.Name("login"))); driver.GetScreenshot().SaveAsFile("1.png", ScreenshotImageFormat.Png); MessageBox.Show("ok"); driver.FindElement(By.Name("email")).SendKeys(txtUserName.Text); driver.FindElement(By.Name("pass")).SendKeys(txtPassWord.Text); driver.FindElement(By.Name("login")).Click(); Thread.Sleep(5000); //WebDriverWait wait2 = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); //IWebElement myDynamicElement2 = wait2.Until<IWebElement>(d => d.FindElement(By.CssSelector("input[name='q']"))); // driver.GetScreenshot().SaveAsFile("2.png", ScreenshotImageFormat.Png); MessageBox.Show("login ok"); // driver.FindElement(By.Id("loginbutton")).Click(); //Thread.Sleep(5000); // Please, replace me with WebDriverWait ^_^ //tao foder if (System.IO.Directory.Exists(txtStringFoder.Text) == false) { System.IO.Directory.CreateDirectory(txtStringFoder.Text); } else { MessageBox.Show("co r"); } //note selenium https://automatetheplanet.com/selenium-webdriver-csharp-cheat-sheet/ //wait selenium while (driver.PageSource=="") { Thread.Sleep(1000); } orr while (true) { string js = "return document.readyState;"; var x = ((IJavaScriptExecutor)driver).ExecuteScript(js).ToString(); if(x== "complete") { break; } // MessageBox.Show(x); // Console.WriteLine(x); Thread.Sleep(500); } orr while (true) { try { js = "document.querySelectorAll('.button')[6].click();"; ((IJavaScriptExecutor)driver).ExecuteScript(js); break; } catch { } Thread.Sleep(500); } //login fb selenium ChromeDriverService service = ChromeDriverService.CreateDefaultService(); service.HideCommandPromptWindow = true; var options = new ChromeOptions(); options.AddArgument("start-maximized"); //options.AddArgument("--headless"); //don't load image // options.AddUserProfilePreference("profile.default_content_setting_values.images", 2); // options.AddArgument("--user-agent=Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14"); var driver = new ChromeDriver(service, options); //checkbox driver.Navigate().GoToUrl("https://www.facebook.com/login.php"); string userName = "nghiahsgs"; string password = "zzzzz"; while (true) { try { driver.FindElement(By.Name("email")).SendKeys(userName); break; } catch { } Thread.Sleep(500); } while (true) { try { driver.FindElement(By.Name("pass")).SendKeys(password); break; } catch { } Thread.Sleep(500); } while (true) { try { driver.FindElement(By.Name("login")).Click(); break; } catch { } Thread.Sleep(500); } //c2 String readyState = "false"; while (readyState == "false") { string js0 = "return document.readyState == 'complete'"; readyState = ((IJavaScriptExecutor)driver).ExecuteScript(js0).ToString(); //MessageBox.Show(readyState); } //wait selenium via javascript var xwait= ((IJavaScriptExecutor)driver).ExecuteScript("return document.querySelector('.search_promotion.btn.btn-danger')"); while (xwait == "null") { xwait= ((IJavaScriptExecutor)driver).ExecuteScript("return document.querySelector('.search_promotion.btn.btn-danger')"); Thread.Sleep(500); } //get text selenium String text=driver.FindElement(By.CssSelector("html")).Text; //String kq=driver.FindElement(By.TagName("pre")).GetProperty("innerText").ToString(); MessageBox.Show(text); //get all file in foder DirectoryInfo d = new DirectoryInfo(txtInputFolder.Text); foreach (var file in d.GetFiles("*.txt")) { //Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name); MessageBox.Show(file.Name); } //move file DirectoryInfo d = new DirectoryInfo(txtInputFolder.Text); foreach (var file in d.GetFiles("*.txt")) { //Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name); // MessageBox.Show(file.Name); // Directory.Move(file.FullName, txtDoneFolder.Text +file.Name); txtFileconfigAuto.Text = file.FullName; btnStartAuto_Click(sender, e); } //update excel private void button1_Click(object sender, EventArgs e) { UpdateExcel(@"D:\testToolTuanHcm\Thumucinput\son moi\listViewAllUid.xlsx",3, 3, "nghiahsgs"); } private void UpdateExcel(String filePath,int row, int col, string data) { Microsoft.Office.Interop.Excel.Application oXL = null; Microsoft.Office.Interop.Excel._Workbook oWB = null; Microsoft.Office.Interop.Excel._Worksheet oSheet = null; try { oXL = new Microsoft.Office.Interop.Excel.Application(); oWB = oXL.Workbooks.Open(filePath); oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Worksheets.get_Item(1); ; oSheet.Cells[row, col] = data; oWB.Save(); // MessageBox.Show("Done!"); } catch (Exception ex) { // MessageBox.Show(ex.ToString()); } finally { if (oWB != null) oWB.Close(); } } //key value - add cookie to selenum https://stackoverflow.com/questions/2745342/how-to-insert-an-item-into-a-key-value-pair-object List<KeyValuePair<string, string>> kvpList = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("sb", "o7ECWngiXWqiVs6hf2JboRMv"), new KeyValuePair<string, string>("c_user", "100006526419466"), new KeyValuePair<string, string>("xs", "33%3A1yxZNFYk10cqEA%3A2%3A1510125987%3A9404%3A6383"), new KeyValuePair<string, string>("fr", "09NOQLsbfG0hAbuvo.AWU-df7wyPsjIApKoiNmxOCrXb0.BaArGj.MV.AAA.0.0.BaArGj.AWUaP1xs"), new KeyValuePair<string, string>("pl", "n"), }; /*kvpList.Insert(0, new KeyValuePair<string, string>("New Key 1", "New Value 1")); kvpList.Insert(0, new KeyValuePair<string, string>("sb", "o7ECWngiXWqiVs6hf2JboRMv")); kvpList.Insert(0, new KeyValuePair<string, string>("c_user", "100006526419466")); kvpList.Insert(0, new KeyValuePair<string, string>("xs", "33%3A1yxZNFYk10cqEA%3A2%3A1510125987%3A9404%3A6383")); kvpList.Insert(0, new KeyValuePair<string, string>("fr", "09NOQLsbfG0hAbuvo.AWU-df7wyPsjIApKoiNmxOCrXb0.BaArGj.MV.AAA.0.0.BaArGj.AWUaP1xs")); kvpList.Insert(0, new KeyValuePair<string, string>("pl", "n"));*/ foreach (KeyValuePair<string, string> kvp in kvpList) { Cookie cookie = new OpenQA.Selenium.Cookie(kvp.Key, kvp.Value); driver.Manage().Cookies.AddCookie(cookie); } //random text var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var stringChars = new char[8]; var random = new Random(); for (int i = 0; i < stringChars.Length; i++) { stringChars[i] = chars[random.Next(chars.Length)]; } var finalString = new String(stringChars); MessageBox.Show(finalString); //ref active key system.Management //time out func var task = Task.Run(() => HamRegApppleId(driver,emailRegAppleId, txtUserNameFastMail.Text, txtPasswordFastmail.Text, StringcomboBoxCOuntry)); if (task.Wait(TimeSpan.FromSeconds(120))) { }else { //throw new Exception("Timed out"); driver.Quit(); } //autoit AutoItX3 au3 = new AutoItX3(); private void button1_Click(object sender, EventArgs e) { au3.MouseMove(0, 0, 10); au3.Sleep(100); if (au3.error == 0) { MessageBox.Show("Success!"); } } //array list\ ArrayList al = new ArrayList(); for (int i = 0; i < richTextBox3.Lines.Count(); i++) { // MessageBox.Show(richTextBox1.Lines[i]); string idFr = richTextBox3.Lines[i]; al.Add(idFr); } for (int i = 0; i < al.Count; i++) { // MessageBox.Show(richTextBox1.Lines[i]); string idFr = al[i].ToString(); } //convert richtextbox to arraylist (big data) var lines = richTextBoxUidSpam.Lines; ArrayList al = new ArrayList(); al.AddRange(lines); MessageBox.Show(al.Count.ToString());
  The post note C# appeared first on Nghiahsgs.
0 notes