Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell vs C# EscapeUriString different results

I have the following problem when using standard C# code and command:

Uri.EscapeUriString("[]")

I get :

"[]"

but when I'm using PowerShell:

[Uri]::EscapeUriString("[]") 

I get

"%5B%5D"

Could someone please explain me what the differences are in those method calls? And why am I getting different results? How to force PowerShell to return the same results as standard c#? Thanks in advance

like image 867
Yawe Avatar asked Oct 01 '18 10:10

Yawe


People also ask

Is PowerShell faster than C?

C is by far the fastest of them all.

Is PowerShell similar to C?

PowerShell has syntax that is related to 'C' languages. It is not a C language and does not work like any C language. PowerShell can create as many array dimensions as you want very easily.

Is C# better than PowerShell?

I might hear someone say (or write) that PowerShell is not as performant than C#, so C# is better. This is… irrelevant, If we are scripting a task to be automated and repeated than performance is likely secondary and writing a nice easy to read and maintain script is what matters.

Is PowerShell written in C#?

Although PowerShell Cmdlets are usually written in PowerShell, there are occasions when the level of integration with existing C# or VB libraries is awkward to achieve with PowerShell.


1 Answers

This seems to be .NET version related. Your C# code probably uses a more recent version.

C#

// .NET 4.0
Uri.EscapeUriString("[]"); // OUTPUT: "%5B%5D"

// .NET 4.5
Uri.EscapeUriString("[]"); // OUTPUT: "[]"

PowerShell

# v5
[Uri]::EscapeUriString("[]") # OUTPUT: "%5B%5D"

# for reference
Add-Type "
using System;
namespace PowerShell
{
    public static class Uri
    {
        public static string EscapeUriString(string stringToEscape)
        {
            return System.Uri.EscapeUriString(stringToEscape);
        }
    }
}"
[PowerShell.Uri]::EscapeUriString("[]") # OUTPUT: "%5B%5D"

There is no "Standard C#". The solution would be to make sure both are using the same .NET version, or implement your own escape method.

Alternatively, use System.Net.WebUtility.UrlEncode which seems to return "%5B%5D" in both cases.

like image 133
marsze Avatar answered Oct 28 '22 14:10

marsze