如何从在线文件.text获取文本

时间:2015-08-21 21:29:46

标签: c# winforms notifications push-notification

我正在使用C#创建一个应该应该从这个位置的文件(在线找到)下载数据作为文本的应用程序:http://asap.eb2a.com/a.text

我只需要获取文本数据。到目前为止我的代码:

//  this.Hide();
//  notifyIcon1.Visible = true;
WebClient Get= new WebClient();
Uri Line = new Uri("http://asap.eb2a.com/a.text");
AAA:
var text = Get.DownloadData(Line);
// var text = System.IO.File.ReadAllText(@"D:\b.txt");
//System.IO.File.Delete(@"D:\Not.text");
label1.Text = text.ToString();
while (text.ToString() == text.ToString())
try
{
    notifyIcon1.Visible = true;
    notifyIcon1.BalloonTipText = (Convert.ToString(text));
    notifyIcon1.BalloonTipTitle = "We Notify You";
    notifyIcon1.ShowBalloonTip(150);
    BBB:   var text1  = Get.DownloadData(Line);
    //System.IO.File.ReadAllText(@"D:\b.txt");
    while(text.ToString()==text1.ToString())
    {
        await Task.Delay(50);
        goto BBB;
    }
    await Task.Delay(50);
    goto AAA; 
}
catch
{
    MessageBox.Show("Error");
}

为了确保数据不一样,我做了一些循环,我在Notify Error With Notification 中得到了这个

1 个答案:

答案 0 :(得分:1)

我认为您的问题是通知图标文本中显示的HTML文本。可能该网站(asap.eb2a.com ...)不允许使用未知代理,因此它会返回一些消息通知您,或者a.text文件包含HTML和JavaScript代码。第一个问题可以通过添加header to the WebClient object来屏蔽您的通话,就好像它来自网络浏览器一样:

Get.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

使用goto/label构造创建的循环可以替换为System.Timers.Timer class。这也将简化您的代码:

  • 创建WebClient对象以调用uri
  • 创建一个变量以保留下载的文本
  • 创建一个计时器对象并绑定Elapsed事件,该事件每100毫秒调用
  • 计时器Elapsed事件中的
  • 使用WebClient.DownloadString方法从网站下载数据
  • 将已保存的文本与新下载的字符串进行比较:如果它们不同,则显示通知图标

实现如下:

WebClient Get = new WebClient();
// identify your self as a web browser
Get.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
Uri uri = Uri("http://asap.eb2a.com/a.text");
string contentToShow = String.Empty;
// timer for the repetitive task called every nnn milliseconds
const long refreshIntervalInMilliseconds = 100;
System.Timers.Timer timer = new System.Timers.Timer(refreshIntervalInMilliseconds);
timer.Elapsed += (s, e) =>
{
    Console.WriteLine(String.Format("{0} Fetching data from: {1}", DateTime.Now, uri));
    try
    {           
        var result = Get.DownloadString(uri);
        if (result != contentToShow)
        {
            contentToShow = result;
            notifyIcon1.Visible = true;
            notifyIcon1.BalloonTipText = contentToShow;
            notifyIcon1.BalloonTipTitle = "We Notify You";
            notifyIcon1.ShowBalloonTip(150);
        }
    }
    catch (Exception exception)
    {
        MessageBox.Show(string.Format("Error: {0}", exception.Message));
    }
};
// start the timer
timer.Start();