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

How to Get Text from Online File .text

我正在使用 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");
}

为了确保数据不一样,我做了一些循环,然后在通知中得到了这个

我假设您的问题是通知图标文本中显示的 HTML 文本。可能网站 (asap.eb2a.com...) 不允许未知代理,因此它 returns 一些消息通知您或 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();