如何使用Uri类从URI中提取第一段

时间:2014-09-25 08:42:50

标签: c#

我正在使用Uri类进行应用程序开发,并且需要用户输入的uri的第一部分,它包含http://或http://或ftp://等。 如果不是这样,我必须硬编码才能添加它。

我已经使用谷歌搜索和堆栈溢出搜索了它,但它们没有显示我的确切要求。

string path,downloadURL;
path =  this.savePath.Text;
downloadURL =  this.downloadURL.Text;

// i have done this but it didn't check if already existing .
downloadURL = "http://" + downloadURL;

Uri tmp = new Uri(downloadURL);
//extracts the last element
string EndPathFileName = tmp.Segments.Last();

// something like this but it returns only  '/'.
//string StartPathFileName = tmp.Segments.First();

//Console.WriteLine(StartPathFileName);

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

根据你想要的行为,有一些选择......

您可以检查它是否包含://,这可能足以满足您的需求:

if(!downloadURL.Contains("://"))
    downloadURL = "http://" + downloadURL;

请注意,这样可以使用"rubbish://www.example.com"

等内容

如果您想要更加谨慎,可以检查字符串是否以您预定的值之一开始。例如:

if(!downloadURL.StartsWith("http://") && !downloadURL.StartsWith("https://") && !downloadURL.StartsWith("ftp://"))
    downloadURL = "http://" + downloadURL;

虽然这意味着"rubbish://www.example.com"会变成"http://rubbish://www.example.com"

您可以选择两种选项,但请记住,处理各种用户输入变得非常困难。


最后一个更强大的建议可能如下:

string[] approvedSchemes = new string[] { "http", "https", "ftp" };
string userScheme = "";

if(downloadURL.Contains("://"))
{
    // Get the first scheme defined, we will use this if it is in the approved list.
    userScheme = downloadURL.Substring(0, downloadURL.IndexOf("://"));
    // To cater for multiple :// remove all of them
    downloadURL = downloadURL.Substring(downloadURL.LastIndexOf("://") + 3);
}

// Check if the user defined scheme is in the approved list, if not then set to http.
if(Array.IndexOf(approvedSchemes, userScheme.ToLowerInvariant()) > -1)
    downloadURL = userScheme + "://" + downloadURL;
else
    downloadURL = "http://" + downloadURL;

Here is a working example

答案 1 :(得分:0)

您需要使用Uri.Scheme Property

    Uri baseUri = new Uri("http://www.contoso.com/");
    Console.WriteLine(baseUri.Scheme); //http

    Uri anotherUri = new Uri("https://www.contoso.com/");
    Console.WriteLine(anotherUri.Scheme); //https