首页 > 解决方案 > 当找不到我在顶部指定的网站 url 时,我如何创建 else 或 if 语句在 usrNameLabel 中创建文本

问题描述

所以我想显示 [NOT FOUND] 如果 web 请求没有找到上面字符串指定的 url。

我所做的是一个 HWID 系统来识别当前用户。它结合了 2 个字符串来查找我的 github 存储库,并在该存储库中包含一个以他们的 hwid 为标题的文件,并在其中显示他们的用户名。我想这样做,如果它没有找到它显示未找到的文件/网站 url/git 存储库。

一切都是事先定义的/一切都按其应有的方式工作,但如果找不到 URL,它将崩溃。

或者如果它被删除。如果它没有找到与互联网的连接,也会发生这种情况。但是我有一个修复程序,当在线/离线状态检查返回为离线时,会将文本切换为未连接。

我已经阅读了一些关于 else 语句的内容,据我所知,它需要上面的 if 语句。我那里没有,因为我的代码以前不需要。

有人可以帮我重写吗?

代码:

        private void Form1_Load(object sender, EventArgs e)
        {
            HWID = System.Security.Principal.WindowsIdentity.GetCurrent().User.Value; 
            textBox1.Text = HWID;
            //downloads the username of the user
            WebClient client = new WebClient();
            string GithubRepository = "INSERT GITHUB LINK";
            string GithubRepositoryImg = "INSERT OTHER GITHUB LINK";
            string urlEndInPNG = ".png";
            String strPageCode = client.DownloadString(GithubRepository+=HWID);

            string strProfPicUrl = GithubRepositoryImg += HWID += urlEndInPNG;
            
            usrNameLabel.Text = strPageCode;
// Insert else or if statement that says it to display "[NOT FOUND]" when it doesnt find it.

//my try
else{
            usrNameLabel.Text = "Not Found";
}

找到显示内容的 url 时显示的内容

我已经用谷歌搜索了如何创建一个,但它不起作用请帮忙。谢谢你

标签: c#

解决方案


我认为你需要一个 try-catch 而不是 if/else 语句。

尝试如下:

    private void Form1_Load(object sender, EventArgs e)
    {
        HWID = System.Security.Principal.WindowsIdentity.GetCurrent().User.Value;
        textBox1.Text = HWID;
        //downloads the username of the user
        WebClient client = new WebClient();
        string GithubRepository = "INSERT GITHUB LINK";
        string GithubRepositoryImg = "INSERT OTHER GITHUB LINK";
        string urlEndInPNG = ".png";

        string strPageCode = string.Empty;

        try
        {
            strPageCode = client.DownloadString(GithubRepository += HWID);
        }
        catch (Exception ex)
        {
            usrNameLabel.Text = "Not Found";
        }

        string strProfPicUrl = GithubRepositoryImg += HWID += urlEndInPNG;

        usrNameLabel.Text = string.IsNullOrEmpty(strPageCode) ? usrNameLabel.Text : strPageCode;
    }

当代码抛出异常时,标签的文本将设置为“未找到”,以防找不到您正在搜索的存储库。


推荐阅读