SmartHosts 是一个托管在 googlecode 上的项目,定期更新 hosts 文件,你懂的。为了方便自动更新,不用每次都打开网站,于是尝试用 c# 实现了一下。

实现原理

https://smarthosts.googlecode.com/svn/trunk/hosts 抓取数据,写入本地 hosts。

实现步骤

1.抓取数据

2.判断本地是否有 hosts 文件。没有则直接建立,并写入抓取下来的数据;有则读取

3.比较两个数据的更新时间。时间一样则不更新;不一样则写入新数据替换旧数据

详细逻辑代码

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace AutoUpdateSmartHosts
{
class Program
{
static void Main(string[] args)
{
string smartPath = "https://smarthosts.googlecode.com/svn/trunk/hosts";
//http://sxlf.org/smarthosts.php
string smartHosts;
string smartTime;
string localPath = Environment.SystemDirectory + @"\drivers\etc\hosts";
string localHosts;
string localTime;
string time = @"#UPDATE(.*)";
using (WebClient client = new WebClient())
{
Console.WriteLine("下载smarthosts...");
byte[] bytes = client.DownloadData(smartPath);
smartHosts = Encoding.GetEncoding("utf-8").GetString(bytes);
Console.WriteLine("下载成功,和本地文件对比...");
Regex reg = new Regex(time);
Match m = reg.Match(smartHosts);
smartTime = m.Value;
}
if (!File.Exists(localPath))
{
File.WriteAllText(localPath, smartHosts);
}
else
{
using (StreamReader sr = new StreamReader(localPath))
{
localHosts = sr.ReadToEnd();
}
Regex reg = new Regex(time);
Match m = reg.Match(localHosts);
localTime = m.Value;
if (localTime == smartTime)
{
Console.WriteLine("你的smarthosts已经是最新的了" + localTime);
Console.Read();
}
else
{
FileInfo fi = new FileInfo(localPath);
if (fi.IsReadOnly)
fi.Attributes = FileAttributes.Normal;
Console.WriteLine("备份文件到hosts.bak");
File.Delete(localPath + @".bak");
fi.MoveTo(Environment.SystemDirectory + @"\drivers\etc\hosts.bak");
Console.WriteLine("正在更新...");
reg = new Regex(f);
localHosts = reg.Replace(localHosts, smartHosts);
}
try
{
File.WriteAllText(localPath, localHosts);
Console.WriteLine("更新成功!");
Console.Read();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.Read();
}
}
}
}
}

但是 googlecode 本身就在墙外,为了能够正常的获取数据,我把 SmartHosts 抓取到了我自己的网站上

<?php
$content = file_get_contents("https://smarthosts.googlecode.com/svn/trunk/hosts");
header('Content-Type: text/plain');
echo $content;
?>

标签: