c# - 当找不到我在顶部指定的网站 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 时显示的内容
我已经用谷歌搜索了如何创建一个,但它不起作用请帮忙。谢谢你
解决方案
我认为你需要一个 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;
}
当代码抛出异常时,标签的文本将设置为“未找到”,以防找不到您正在搜索的存储库。
推荐阅读
- reactjs - React 模拟 Graphql 订阅
- java - Sparql 与 Java Jena
- python - TypeError: can't pickle _thread.RLock objects, K.shape 问题
- image - 如何为 Pneu Alpha 函数创建位图:错误位图格式无效。仅选择 16 或 256 色位图
- reactjs - 如果未定义数据,如何传递 null?
- php - SQL Query 运行良好,但现在当我尝试将它与 PHP 一起使用时,查询失败
- redis - 有效地限制 Redis 中两个集合之间的交集结果
- python - 如何制作图标在模板中显示
- cloud - 如何在云环境中操作决策树?
- javascript - 当你点击它时,如何让多个元素消失?