zl程序教程

您现在的位置是:首页 >  后端

当前栏目

记录游客页面访问IP的简易实现代码(asp.net+txt)

NetASPIP代码 实现 访问 记录 页面
2023-06-13 09:14:15 时间
记录处理类
复制代码代码如下:

usingSystem;
usingSystem.IO;

///<summary>
///File
///</summary>
publicclassFile
{
protectedstringFilePath;

///<summary>
///File构造
///</summary>
///<paramname="filePath">需要操作的文本路径</param>
publicFile(stringfilePath)
{
this.FilePath=filePath;
}

///<summary>
///文本内容写入
///</summary>
///<paramname="info">写入内容</param>
publicvoidFileWrite(stringinfo)
{
try
{
FileInfofile=newFileInfo(FilePath);

if(!file.Exists)
{
using(StreamWritersw=file.CreateText())
{
sw.WriteLine(info);
}
}
else
{
using(StreamWritersw=file.AppendText())
{
sw.WriteLine(info);
}
}
}
catch(FileNotFoundExceptionfileCe)
{
throwfileCe;
}
catch(Exceptionce)
{
throwce;
}
}
}

页面调用代码
复制代码代码如下:

publicpartialclass_Default:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
if(!IsPostBack)
{
//判断当前用户是否访问过,只记录未访问过的用户
if(Request.Cookies["IsExitsIP"]==null)
{
//每天一个记事本.txt
stringfileName=string.Format("{0}{1}{2}",DateTime.Now.Year.ToString(),DateTime.Now.Month.ToString(),DateTime.Now.Day.ToString());
Filefile=newFile(Server.MapPath("~/test/"+fileName+".txt"));
file.FileWrite(Request.UserHostName);
//给正在访问的用户添加已访问标记
HttpCookiecokie=newHttpCookie("IsExitsIP");
cokie.Values.Add("ip",Request.UserHostName);
Response.AppendCookie(cokie);
}
}
}
}