I have an application which sends a POST request to the VB forum software and logs someone in (without setting cookies or anything).
Once the user is logged in I create a variable that creates a path on their local machine.
c:\tempfolder\date\username
The problem is that some usernames are throwing "Illegal chars" exception. For example if my username was mas|fenix
it would throw an exception..
Path.Combine( _
Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData), _
DateTime.Now.ToString("ddMMyyhhmm") + "-" + form1.username)
I don't want to remove it from the string, but a folder with their username is created through FTP on a server. And this leads to my second question. If I am creating a folder on the server can I leave the "illegal chars" in? I only ask this because the server is Linux based, and I am not sure if Linux accepts it or not.
EDIT: It seems that URL encode is NOT what I want.. Here's what I want to do:
old username = mas|fenix
new username = mas%xxfenix
Where %xx is the ASCII value or any other value that would easily identify the character.
Better way is to use
Uri.EscapeUriString
to not reference Full Profile of .net 4.
Url Encoding is easy in .NET. Use:
If that'll be decoded to get the folder name, you'll still need to exclude characters that can't be used in folder names (*, ?, /, etc.)
If you can't see System.Web, change your project settings. The target framework should be ".NET Framework 4" instead of ".NET Framework 4 Client Profile"
I have written a C# method that url-encodes ALL symbols:
Edit: Note that this answer is now out of date. See Siarhei Kuchuk's answer below for a better fix
UrlEncoding will do what you are suggesting here. With C#, you simply use
HttpUtility
, as mentioned.You can also Regex the illegal characters and then replace, but this gets far more complex, as you will have to have some form of state machine (switch ... case, for example) to replace with the correct characters. Since
UrlEncode
does this up front, it is rather easy.As for Linux versus windows, there are some characters that are acceptable in Linux that are not in Windows, but I would not worry about that, as the folder name can be returned by decoding the Url string, using
UrlDecode
, so you can round trip the changes.In addition to @Dan Herbert's answer , You we should encode just the values generally.
Split has params parameter Split('&','='); expression firstly split by & then '=' so odd elements are all values to be encoded shown below.