Search code examples
c#html.neturl

Add New Query Strings to Existing URL in C# and Redirect to it


Can anybody help me with the c# code to add two query strings to an existing URL. URL typically looks like this below. When the URL is created in c# to redirect to it as well. Any help much appreciated.

http://localhost/somesite/index.php?Filename=somefile.txt&Filepath=E:\myfolder

Solution

  • to build up url would be option A: (string concat)

    
    string param1 = "Filename=somefile.txt";
        string param2 = @"Filepath=E:\myfolder";
        Uri YourURL = new Uri($"http://localhost/somesite/index.php?{param1}&{param2}");
        Console.WriteLine(YourURL);
    
    

    Option b: (URIBuilder)

    UriBuilder uriBuilder = new UriBuilder();
        uriBuilder.Scheme = "http";
        uriBuilder.Host = "localhost";
        uriBuilder.Path = "somesite/index.php";
        //uriBuilder.Port = 80;
        
        var q = new Dictionary<string,string>();
        q.Add("Filename","somefile.txt");
        q.Add("Filepath","E:\\myfolder");
        uriBuilder.Query = string.Join("&", q.Select(s => $"{s.Key}={s.Value}").ToList());
        uriBuilder.ToString().Dump();
    
    

    to redirect. not sure what are you using for UI. the question is very blur. but to redirect try this:

    Response.Redirect(YourURL);
    

    otherwise, please rewrite your question with better explanation