Easy implementation code of asp.net +txt to record visitor page access to IP
- 2020-05-07 19:31:26
- OfStack
Record processing class
Page calling code
using System;
using System.IO;
/// <summary>
/// File
/// </summary>
public class File
{
protected string FilePath;
/// <summary>
/// File structure
/// </summary>
/// <param name="filePath"> The text path that needs to be manipulated </param>
public File(string filePath)
{
this.FilePath = filePath;
}
/// <summary>
/// Text content write
/// </summary>
/// <param name="info"> Write content </param>
public void FileWrite(string info)
{
try
{
FileInfo file = new FileInfo(FilePath);
if (!file.Exists)
{
using (StreamWriter sw = file.CreateText())
{
sw.WriteLine(info);
}
}
else
{
using (StreamWriter sw = file.AppendText())
{
sw.WriteLine(info);
}
}
}
catch(FileNotFoundException fileCe)
{
throw fileCe;
}
catch (Exception ce)
{
throw ce;
}
}
}
Page calling code
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// To determine whether the current user has accessed, only unaccessed users are recorded
if (Request.Cookies["IsExitsIP"] == null)
{
// Every day, 1 A notepad .txt
string fileName = string.Format("{0}{1}{2}", DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString(), DateTime.Now.Day.ToString());
File file = new File(Server.MapPath("~/test/" + fileName + ".txt"));
file.FileWrite(Request.UserHostName);
// Add the accessed tag to the user being accessed
HttpCookie cokie = new HttpCookie("IsExitsIP");
cokie.Values.Add("ip", Request.UserHostName);
Response.AppendCookie(cokie);
}
}
}
}