tags:

views:

94

answers:

5
+1  Q: 

String Encoding

I am checking for the existence of a file in the XML backup of my iTunes library.

How do I change this string

E:\Entertainment\Music\Latin\100% Azucar The Best of Celia Cruz & La Sonora Matancera/08 Mi Soncito.mp3

to this

E:/Entertainment/Music/Latin/100%25%20Azucar%20%20The%20Best%20of%20Celia%20Cruz%20&%20La%20Sonora%20Matancera/08%20Mi%20Soncito.mp3

Changes:

  1. Space becomes %20
  2. Backslash becomes Forward-slash
  3. % (percentage sign) became %25
+6  A: 

Looks like two separate things:

1) Replacing backslash with forward slash.

2) Applying URI-encoding.

The first is obvious. For the second, you have some choices, including Uri.EscapeDataString, Uri.EscapeUriString, HttpUtility.UrlEncode and HttpUtility.UrlPathEncode.

edit

3) As Vilx noticed, there seems to be HtmlEncoding of the filename portion.

Maybe the best answer is to use the Uri class to slice and dice the parts, encoding them as needed.

Steven Sudit
A: 

%20 means space character. i see that you want to do something more with this string, so may i ask you what tools you'll prefer to use? regex? string replaces?

Tomasz Kowalczyk
that's kind of what he's asking us ;)
jlafay
Tomasz, URI-encoding does replace spaces with `%20`, but it also replaces many other characters. This means `String.Replace` is not a good solution. As for RegExp, that's overkill.
Steven Sudit
that's why i asked what tools he'd prefer, so that i can write proper code ;]
Tomasz Kowalczyk
I think the idea here is that he wants it to work, so he's asking you to select the tool.
Steven Sudit
A: 

You do it with Uri.EscapeDataString() static method. Super easy.

jlafay
No, this will escape the backslashes instead of converting them. In other words, you still need to do a `Replace` first.
Steven Sudit
+2  A: 

A very simple route:

filepath.Replace("\", "/").Replace("%", "%25").Replace(" ", "%20").Replace("&", "&")

Aaron D
This only works for this specific case. When other characters are encoded, this fails.
Steven Sudit
I couldn't find an enconding scheme that matched was iTunes was using, so I had to go this route1
Raj More
+3  A: 

I think I found the key part of his problem. It's kinda hidden there, being the first sentence and all, so nobody noticed it much. XD

I am checking for the existence of a file in the XML backup of my iTunes library.

It seems to me that we are dealing with some rogue iTunes-XML encoding, which has messed up a bit somewhere along the line. My advice would be to go the other way round - decode the iTunes string (first through HtmlDecode, then UrlDecode) and then compare it to the original string you are looking for. This should be able to cope with most mis-encodings of iTunes.

Vilx-