如何将url分成多个字符串部分

时间:2015-11-16 08:34:32

标签: asp.net visual-studio-2010 c#-4.0

我的网址是我的SSRS报告的完整路径。在C#中我想打破多个字符串中的url

http://Mydatabase-live/ReportServer?%2fADMIN%2fSTATS+-+SCHEDULE&TEAMNM=2015 TERRIER JV&rs:Command=Render&rs:Format=PDF

在这里,我想将此网址分解为第1部分http://Mydatabase-live/ReportServer第2部分ADMIN/STATS-SCHEDULE和部分3 TEAMNM

2 个答案:

答案 0 :(得分:1)

我想到了这一点,其中一种方法是为程序定义一些分隔符,以便知道在哪里破解URL。

在我们这样做之前,我们需要先替换特殊字符。

让我们开始吧:

string searchFor;
string replaceWith;

static void Main(string[] args)
{
    // First we need to replace the special characters:
    ReplaceSubstrings replace = new ReplaceSubstrings();
    string s = "http://Mydatabase-live/ReportServer?%2fADMIN%2fSTATS+-+SCHEDULE&TEAMNM=2015 TERRIER JV&rs:Command=Render&rs:Format=PDF";

    // We need to replace:
    // "%2f" with "/"
    // "+-+" with "-"

    // using System.Text.RegularExpressions
    replace.searchFor = "%2f";
    replace.replaceWith = "/";
    s = Regex.Replace(s, replace.searchFor);

    replace.searchFor = "+-+";
    replace.replaceWith = "-";
    s = Regex.Replace(s, replace.searchFor);

    // Your URL will now look like this:

    Console.WriteLine(s);
    // Output: http://Mydatabase-live/ReportServer?/ADMIN/STATS-SCHEDULE&TEAMNM=2015 TERRIER JV&rs:Command=Render&rs:Format=PDF

    // Add the delimiters
    char[] delimiters = {'?', '&', '='};
    string[] words = s.Split(delimiters);

    foreach (string s in words)
    {
        System.Console.WriteLine(s);
    }
    // Output:
    // http://Mydatabase-live/ReportServer
    // /ADMIN/STATS-SCHEDULE
    // TEAMNM
    // 2015 TERRIER JV
    // rs:Command
    // Render
    // rs:Format
    // PDF

    // Keep the console window open in debug mode.
    Console.WriteLine("Press any key to exit");
    Console.ReadKey();
}

您的网址将在比您指定的地方多得多的地方分开,但您应该这样做。您可以从第一个=符号所在的字符串中删除最后一部分,然后执行字符串分隔。

我希望这对你有所帮助。

答案 1 :(得分:1)

这是使用Uri Class分割URL的动态方式。 Uri类具有获取绝对路径,查询等功能。您可以使用它们来构建您的需求。

        string path = "http://Mydatabase-live/ReportServer?%2fADMIN%2fSTATS+-+SCHEDULE&TEAMNM=2015 TERRIER JV&rs:Command=Render&rs:Format=PDF";
        Uri uri = new Uri(path);
        Console.WriteLine(uri.AbsolutePath); //Absolute path
        Console.WriteLine(uri.Query); //Query
相关问题