Josh
Josh

Reputation: 1901

URL breaking at special character

I'm having trouble with a URL string in my Web Application. It's using a UNC path similar to \\houtestmachine\common\File1.pdf My problem is when it encounters files that have a # character. I tried doing a string newstring = originalstring.Replace("#", "%23"); but the # is still there in URL (target of a hyperlink) at runtime in the browser. How can I fix this?

Upvotes: 1

Views: 1663

Answers (3)

Hans Passant
Hans Passant

Reputation: 941218

You are converting between file system paths and URLs. The Uri class should fit the bill:

using System;

class Program {
  static void Main(string[] args) {
    var url = new Uri(@"\\houtestmachine\common\F#ile1.pdf");
    Console.WriteLine(url.AbsoluteUri);
    var back = url.LocalPath;
    Console.WriteLine(back);
    Console.ReadLine();
  }
}

Output:

file://houtestmachine/common/F%23ile1.pdf
\\houtestmachine\common\F#ile1.pdf

Upvotes: 2

Constantine
Constantine

Reputation: 228

Use symbol @ befor string. For example

string st = @"your#path"

Upvotes: 0

Mike Marshall
Mike Marshall

Reputation: 7850

Have you tried HttpUtility.UrlEncode()?

Upvotes: 1

Related Questions