温馨提示×

C#如何获取网络路径的实际应用

c#
小樊
83
2024-06-25 00:24:33
栏目: 编程语言

在C#中,可以使用System.Net.WebRequest类来获取网络路径的实际应用。以下是一个简单的示例代码,演示如何获取指定URL的实际路径:

using System;
using System.Net;

class Program
{
    static void Main()
    {
        string url = "http://www.example.com";
        
        try
        {
            WebRequest request = WebRequest.Create(url);
            request.Method = "HEAD";

            using (WebResponse response = request.GetResponse())
            {
                string actualUrl = response.ResponseUri.AbsoluteUri;
                Console.WriteLine("Actual URL: " + actualUrl);
            }
        }
        catch (WebException ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }
}

在上面的示例中,我们创建了一个WebRequest对象,并设置了要请求的URL。然后,我们发送一个HEAD请求,并获取响应的实际URL。最后,我们将实际URL打印到控制台上。

请注意,如果指定的URL重定向到另一个URL,则实际URL可能与输入URL不同。因此,使用WebRequest类可以帮助我们获取网络路径的实际应用。

0