C#获取Exception errorCode

本文介绍了一种使用try-catch结构进行异常处理的方法,并详细展示了如何从捕获到的异常中获取Win32异常的具体信息,以便进一步判断错误类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

            try
            {

                //代码
            }
            catch(Exception e)
            {
                var w32ex = e as Win32Exception;
                if (w32ex == null)
                {
                    w32ex = e.InnerException as Win32Exception;
                }
                if (w32ex != null)
                {

                    //根据code来判别错误
                    int code = w32ex.ErrorCode;
                } 
            }

### C# 获取公网IP地址的方法 在C#中,可以通过访问外部服务来获取设备的公网IP地址。这些外部服务通常会返回当前网络环境下的公网IP地址。以下是实现这一功能的一种方法: #### 方法描述 通过调用HTTP请求到特定的服务端接口(例如 `httpbin.org` 或其他提供公网IP查询的服务),可以轻松获得当前客户端的公网IP。 #### 示例代码 以下是一个完整的示例代码片段,展示如何使用C#中的 `HttpClient` 类发送GET请求并解析响应数据以提取公网IP地址: ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class PublicIPAddressFetcher { private const string IpServiceUrl = "https://api64.ipify.org?format=json"; // 使用支持JSON格式的API public static async Task<string> GetPublicIPAddressAsync() { try { using HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync(IpServiceUrl); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); // 假设返回的数据结构为 {"ip":"<PUBLIC_IP>"} int startIndex = responseBody.IndexOf(":") + 2; // 跳过 ":" int endIndex = responseBody.Length - startIndex - 2; // 减去最后的 "}" return responseBody.Substring(startIndex, endIndex).Trim('"'); } else { throw new Exception($"Failed to retrieve public IP address. Status Code: {response.StatusCode}"); } } catch (Exception ex) { Console.WriteLine($"An error occurred while fetching the public IP: {ex.Message}"); return null; } } public static void Main(string[] args) { Task.Run(async () => { string publicIp = await GetPublicIPAddressAsync(); if (!string.IsNullOrEmpty(publicIp)) { Console.WriteLine($"Your public IP address is: {publicIp}."); } }).GetAwaiter().GetResult(); } } ``` 此代码实现了异步操作,并利用了现代C#特性如 `HttpClient` 和 JSON 数据处理[^3]。 --- #### 关键点说明 1. **外部服务的选择** 上述代码使用的 API 是来自 `ipify` 的免费服务,它提供了简单的 HTTP 接口用于检索用户的公网IP地址。如果需要更复杂的场景或者更高的可靠性,可以选择其他类似的第三方服务[^4]。 2. **异常处理** 在实际应用中,建议增加更多的错误捕获逻辑以及重试机制,以便在网络不稳定的情况下提高程序健壮性。 3. **同步 vs 异步** 如果项目允许,则推荐采用异步方式执行网络请求;但如果必须保持简单流程控制,也可以考虑阻塞式的同步版本。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值