26

I am generating a relative path from 1 directory to another. If the OutputDirectoryName property is a directory containing spaces, the spaces are encoded using %20, rather than a space. I am creating a relative path to a windows folder, so I must have my relatiave path using spaces. Is there a clean way to specify how the URI is encoded? I know I could do a stirng replace on the relativePath.ToString(), but am wondering if there's a better implementation. Thanks.

public string GetOutputDirectoryAsRelativePath(string baseDirectory)
{
    Uri baseUri = new Uri(baseDirectory);
    Uri destinationUri = new Uri(OutputDirectoryName);
    Uri relativePath = baseUri.MakeRelativeUri(destinationUri);
    return relativePath.ToString();
}
casperOne
  • 73,706
  • 19
  • 184
  • 253
Stealth Rabbi
  • 10,156
  • 22
  • 100
  • 176
  • Why do you need to replace the %20 with a space ? That is the correct way to represent a space in a URI. If you pass the strings to code that is expecting URIs then it will know that %20 means space. – andynormancx Apr 18 '11 at 17:32
  • 3
    @andy: He probably wants a Windows file path, which is not URL-encoded. – SLaks Apr 18 '11 at 17:33
  • 1
    @SLarks, that's correct. @andynormancx, "I am creating a relative path to a windows folder" – Stealth Rabbi Apr 18 '11 at 17:41
  • 3
    Simply replacing the %20 is definitely not the way to go. There are other valid characters in Windows paths that will be encoded by the Uri class. Using Uri.UnescapeDataString looks like the best bet to me. – andynormancx Apr 18 '11 at 17:46
  • @andy, you are correct. This isn't in the Answers section, so it has to go to Darth. Thank you! – Stealth Rabbi Apr 18 '11 at 17:54

4 Answers4

41

You can use

Uri.UnescapeDataString

http://msdn.microsoft.com/en-us/library/system.uri.unescapedatastring.aspx

derHugo
  • 83,094
  • 9
  • 75
  • 115
darth happyface
  • 2,687
  • 2
  • 20
  • 15
2

Use HttpServerUtility.UrlDecode Method (String)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tomas Voracek
  • 5,886
  • 1
  • 25
  • 41
2
string sRelativeFilePath = Uri.UnescapeDataString(new Uri(sAbsolutePath + "\\", false).MakeRelative(new Uri(filename)));
Nisha
  • 1,783
  • 4
  • 18
  • 34
1

Try looking at Server.UrlDecode: http://msdn.microsoft.com/en-us/library/6196h3wt.aspx

The space character is not the only one that is encoded.

Jason Kealey
  • 7,988
  • 11
  • 42
  • 55