1

I need to launch a URL from my application that includes quotes, like the following:

string TheURL = "http://www.google.com/search?hl=en&q=hello world \"" + "test with quotes\"";

So this will search Google for:

hello world "test with quotes"

I'm opening this in the user's default web browser by using the Process.Start command:

System.Diagnostics.Process.Start(TheURL);

However, this command fails to do anything if Firefox is set as my default browser, and it launches three separate tabs if Chrome is my default browser. Does anyone know how you can pass quotes to the Process.Start command?

Tudor
  • 61,523
  • 12
  • 102
  • 142
andrewl85
  • 199
  • 1
  • 4
  • 11
  • See [This question](http://stackoverflow.com/questions/4820167/url-encoding-quotes-and-spaces) – spots Aug 17 '12 at 17:26

3 Answers3

4

EDIT: Suggestion from commenter applied!

You use Uri.EscapeUriString: http://msdn.microsoft.com/en-us/library/system.uri.escapeuristring.aspx

string search = @"Bill & Ted's Excellent Adventure";
string ActualURL = "http://www.google.com/search?hl=en&q=" + Uri.EscapeDataString(search);
System.Diagnostics.Process.Start(ActualURL);

EDIT2: Apparently my code was broken. It wouldn't allow for searches that contained the ampersand character. Fixed the code above; now works for regular code and code with ampersands.

Ted Spence
  • 2,598
  • 1
  • 21
  • 21
  • 1
    `Uri.EscapeUriString` does same job and works under .net client profile, so is more portable. http://msdn.microsoft.com/en-us/library/system.uri.escapedatastring.aspx – spender Aug 17 '12 at 17:42
  • Good to know! Silly me, I've been writing this same code since 1997 and I immediately think HttpUtility.UrlEncode from original ASP days ;) – Ted Spence Aug 17 '12 at 17:47
3

Personally, I like to use URI. It allows a lot of flexibility with encoding/decoding and practically no effort.

        Uri myUri = new Uri("http://google.com/search?hl=en&q=\"hello world\"");
        System.Diagnostics.Process.Start(myUri.AbsoluteUri);
P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348
  • You are right. This worked without much effort at all, and it seems to be easier than using HttpServerUtility.UrlEncode. Thank you very much, sir. – andrewl85 Aug 17 '12 at 18:03
  • As near as I can tell, the Uri approach fails if your string contains an ampersand - is that right? I tried this: `Uri myUri = new Uri("http://google.com/search?movie=bill & ted's excellent adventure");` - instead, I got the google search for `bill `. – Ted Spence Aug 21 '12 at 21:48
2

This is simply not a valid URL, you can't open/launch it.

URL encode the components before composing it, using System.Web.HttpUtility.UrlEncode.

Reference : http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758