我有一个 Windows 服务,我想在调用构造函数时更改 URL。我通过将变量连接到构造函数中来形成 URL,并且变量正在递增(如下面的代码所示)。
但是,URL 没有改变,我仍然从 URL 下载相同的 XML 文件。
我试过这个:
private string Url;
private string Name = @"D:\test\userko.xml";
private System.Timers.Timer timer;
private Downloader xd;
private static int i;
public Service1()
{
InitializeComponent();
while (i < 5000)
{
Url = "http://tis-toolbox.appspot.com/api/user/id/" + i + ".xml";
i++;
if (i == 4999)
i = 0;
break;
}
xd = new Downloader(Url, Name);
timer = new System.Timers.Timer();
timer.Enabled = true;
timer.Interval = 1000;
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
}
protected override void OnStart(string[] args)
{
EventLog.WriteEntry("PCTrss reader Service Started.");
tryDownload();
}
protected override void OnStop()
{
EventLog.WriteEntry("PCTrss reader Service was shutdown.");
}
private void timer_Elapsed(object sender, EventArgs e)
{
tryDownload();
}
private void tryDownload()
{
try
{
timer.Stop();
xd.DownloadXML();
EventLog.WriteEntry("PCTrss reader downloaded news at " + xd.LastUpdate + ". XML is in " + Name);
}
catch (Exception ex)
{
EventLog.WriteEntry("PCTrss reader Service cannot download feeds " + ex.ToString());
}
finally
{
timer.Start();
}
}
}
这是下载器类。它从 URL 读取并保存 XML 文件。
class Downloader
{
public DateTime LastUpdate;
public string Url { get; set; }
public string Name { get; set; }
public Downloader(string url, string name)
{
this.Url = url;
this.Name = name;
}
public void DownloadXML()
{
if (!Directory.Exists(@"D:\test"))
Directory.CreateDirectory(@"D:\test");
LastUpdate = DateTime.Now;
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
using( Stream stream = client.OpenRead(Url) )
using( StreamReader sr = new StreamReader(stream) )
using( FileStream fs = new FileStream(Name, FileMode.Create, FileAccess.Write))
using( StreamWriter sw = new StreamWriter(fs) )
{
string s = sr.ReadToEnd();
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.Write(s);
}
}
}