//投票 PRotected void btn_Vote_Click(object sender, EventArgs e) { string useripAddress = Request.UserHostAddress.ToString();//獲取用戶本地的IP地址 HttpCookie oldCookie=Request.Cookies["UserIP"];//創建Cookie對象 if (oldCookie == null)//該用戶沒有投票記錄 { int flag = this.rbl_Evaluate.SelectedIndex;//獲取用戶投票的選項 switch (flag) { case 0: AddCount(Server.MapPath("Result1.txt")); break; case 1: AddCount(Server.MapPath("Result2.txt")); break; case 2: AddCount(Server.MapPath("Result3.txt")); break; default: break; } Page.RegisterClientScriptBlock("", "<script>alert('投票成功,謝謝您的參與')<script>"); HttpCookie newCookie = new HttpCookie("UserIP");//創建新的Cookie對象 newCookie.Expires = DateTime.MaxValue;//設置Cookie的有效時間 newCookie.Values.Add("IPAddress", userIpAddress);//添加用戶的IP地址在Cookie中,保存起來 Response.AppendCookie(newCookie);//將變量寫入Cookie文件中 } else { string userOldAddress = oldCookie.Values["IPAddress"].ToString(); if (userIpAddress.Trim() == userOldAddress.Trim())//創建Cookie對象 { Page.RegisterClientScriptBlock("", "<script>alert('每天只能投票一次,謝謝您的光顧!!')</script>"); } else { HttpCookie newCookie = new HttpCookie("UserIP");//創建新的Cookie對象 newCookie.Values.Add("IpAddress", userIpAddress); newCookie.Expires = DateTime.MaxValue; Response.AppendCookie(newCookie); int flag = this.rbl_Evaluate.SelectedIndex; switch (flag) { case 0: AddCount(Server.MapPath("Result1.txt")); break; case 1: AddCount(Server.MapPath("Result2.txt")); break; case 2: AddCount(Server.MapPath("Result3.txt")); break; default: break; } Page.RegisterClientScriptBlock("", "<script>alert('投票成功謝謝您的參與')</script>"); } } }
/// <summary> /// 讀取文本文件中的數字 /// </summary> /// <param name="str_path">文本文件的路徑</param> /// <returns>返回結果</returns> protected static int ReadCount(string str_path) { int count = 0;//創建整形的變量 System.IO.StreamReader srd;//創建流讀取對象 srd = System.IO.File.OpenText(str_path);//打開指定的文本文件 if (srd.Peek()!=-1)//如果有數據 { count = int.Parse(srd.ReadLine());//讀取文本文件的數字賦值給count } srd.Close();//關閉流對象 return count; }
/// <summary> /// 對現有的投票數進行增加 /// </summary> /// <param name="str_path">文本文件的路徑</param> protected static void AddCount(string str_path) { int count = ReadCount(str_path); count += 1; System.IO.StreamWriter swr = new System.IO.StreamWriter(str_path);//將數據的記錄寫入文件 swr.WriteLine(count); swr.Close(); }
新聞熱點
疑難解答