基本信息
源码名称:hosts 修改实例源码
源码大小:4.50KB
文件格式:.cs
开发语言:C#
更新时间:2013-10-29
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 10 元×
微信扫码支付:10 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
//删除指定域名的所有映射 throws Exception private void DeleteHostMapping(string strDomain) { if (!File.Exists(hostMappingFile)) { MessageBox.Show("未执行删除!\n文件不存在:\n" hostMappingFile, "提示"); return; } //有效映射行(行首到IP地址之间有0个以上空白字符,IP与域名间有1个以上空白字符,行末0个以上注释) Regex regMapping = new Regex(@"^\s*\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s " strDomain @"\s*(#.*)*$"); //待写入文件的内容 StringBuilder sbFinalContent = new StringBuilder(); //待删除域名映射(正常情况下只会有一条记录,考虑文件被手工修改的情况,需要删除全部映射,新的域名映射才会生效) List<string> host2Delete = new List<string>(); //删除(读取系统原有映射,过滤掉指定域名的映射) using (StreamReader sr = new StreamReader(hostMappingFile)) { string tmpLine = sr.ReadLine(); while (tmpLine != null) { if (regMapping.IsMatch(tmpLine)) { host2Delete.Add(tmpLine); } else { sbFinalContent.Append(tmpLine); sbFinalContent.AppendLine(); } tmpLine = sr.ReadLine(); } } //不存在,所以文件没做更改,无需写入覆盖 if (host2Delete.Count==0) { MessageBox.Show("指定域名不存在!", "提示"); return; } StringBuilder sbConfirmMsg = new StringBuilder(); sbConfirmMsg.Append("以下域名将被删除:\n"); foreach (string host in host2Delete) { sbConfirmMsg.Append(host); sbConfirmMsg.AppendLine(); } if (MessageBox.Show(sbConfirmMsg.ToString(), "确认", MessageBoxButtons.OKCancel) != DialogResult.OK) { return; } using (StreamWriter sw = new StreamWriter(hostMappingFile)) { sw.Write(sbFinalContent.ToString()); } MessageBox.Show("删除成功!", "提示"); } //添加新映射 throws Exception private void AddNewHostMapping(string strDomain, string strIP, string strRemark) { //待写入文件的内容 StringBuilder sbFinalContent = new StringBuilder(); //读取系统原有映射(同时检验所添加的映射是否已存在) if (File.Exists(hostMappingFile)) { //有效映射行(行首到IP地址之间有0个以上空白字符,IP与域名间有1个以上空白字符,行末0个以上注释) Regex regMapping = new Regex(@"^\s*\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s " strDomain @"\s*(#.*)*$"); using (StreamReader sr = new StreamReader(hostMappingFile)) { string tmpLine = sr.ReadLine(); while (tmpLine != null) { if (regMapping.IsMatch(tmpLine)) { MessageBox.Show("域名已存在:\n" tmpLine, "提示"); return; } sbFinalContent.Append(tmpLine); sbFinalContent.AppendLine(); tmpLine = sr.ReadLine(); } } } StringBuilder sbNewMapping = new StringBuilder(); sbNewMapping.Append(strIP.PadRight(15));//IP长度对齐,易读 sbNewMapping.Append(" "); sbNewMapping.Append(strDomain); sbNewMapping.Append(" #"); sbNewMapping.Append(strRemark); sbNewMapping.Append(" added "); sbNewMapping.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); if (MessageBox.Show("添加域名:\n" sbNewMapping.ToString(), "确认", MessageBoxButtons.OKCancel) != DialogResult.OK) { return; } //新映射 sbFinalContent.Append(sbNewMapping); using (StreamWriter sw = new StreamWriter(hostMappingFile)) { sw.Write(sbFinalContent.ToString()); } MessageBox.Show("添加成功!", "提示"); }