URL Encoding using C#

前端 未结 13 1944
北荒
北荒 2020-11-22 08:05

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 cre

13条回答
  •  伪装坚强ぢ
    2020-11-22 08:49

    Ideally these would go in a class called "FileNaming" or maybe just rename Encode to "FileNameEncode". Note: these are not designed to handle Full Paths, just the folder and/or file names. Ideally you would Split("/") your full path first and then check the pieces. And obviously instead of a union, you could just add the "%" character to the list of chars not allowed in Windows, but I think it's more helpful/readable/factual this way. Decode() is exactly the same but switches the Replace(Uri.HexEscape(s[0]), s) "escaped" with the character.

    public static List urlEncodedCharacters = new List
    {
      "/", "\\", "<", ">", ":", "\"", "|", "?", "%" //and others, but not *
    };
    //Since this is a superset of urlEncodedCharacters, we won't be able to only use UrlEncode() - instead we'll use HexEncode
    public static List specialCharactersNotAllowedInWindows = new List
    {
      "/", "\\", "<", ">", ":", "\"", "|", "?", "*" //windows dissallowed character set
    };
    
        public static string Encode(string fileName)
        {
            //CheckForFullPath(fileName); // optional: make sure it's not a path?
            List charactersToChange = new List(specialCharactersNotAllowedInWindows);
            charactersToChange.AddRange(urlEncodedCharacters.
                Where(x => !urlEncodedCharacters.Union(specialCharactersNotAllowedInWindows).Contains(x)));   // add any non duplicates (%)
    
            charactersToChange.ForEach(s => fileName = fileName.Replace(s, Uri.HexEscape(s[0])));   // "?" => "%3f"
    
            return fileName;
        }
    

    Thanks @simon-tewsi for the very usefull table above!

提交回复
热议问题