Skip to main content
improve code formatting
Source Link
spottedmahn
  • 16.2k
  • 21
  • 124
  • 204
    public static string ExecuteCurl(string curlCommand, int timeoutInSeconds=60)
{
    if (string.IsNullOrEmpty(curlCommand))
        return "";

    curlCommand = curlCommand.Trim();

    // remove the curl keworkd
    if (curlCommand.StartsWith("curl"))
    {
        ifcurlCommand (string= curlCommand.IsNullOrEmptySubstring(curlCommand"curl".Length).Trim();
            return "";}

    // this code only works on windows 10 or higher
    {
        
        curlCommand = curlCommand.TrimReplace("--compressed", "");

        // removewindows the10 curlshould keworkdcontain this file
        var fullPath = System.IO.Path.Combine(Environment.SystemDirectory, "curl.exe");

        if (curlCommandSystem.StartsWithIO.File.Exists("curl"fullPath) == false)
        {
            curlCommand =if curlCommand.Substring("curl"Debugger.LengthIsAttached) { Debugger.TrimBreak(); }
            throw new Exception("Windows 10 or higher is required to run this application");
        }

        // this code only works on windows 10 or higher
 ' are not supported. For example: curl {
'http://ublux.com' does not work and it needs to be replaced to curl "http://ublux.com"
           List<string> curlCommandparameters = curlCommand.Replace("--compressed",new ""List<string>();

            // windows 10 should contain this file
            var fullPath = System.IO.Path.Combine(Environment.SystemDirectory, "curl.exe");

        // separate parameters to ifescape (System.IO.File.Existsquotes
        try
        {
            Queue<char> q = new Queue<char>(fullPath);

 == false          foreach (var c in curlCommand.ToCharArray())
            {
                if (Debugger.IsAttached) { Debuggerq.Break(); }
                throw new ExceptionEnqueue("Windows 10 or higher is required to run this application"c);
            }

            // on windows ' are not supported. For example: curl 'http://ublux.com' does not work and it needs to be replaced to curl "http://ublux.com"
            List<string>StringBuilder parameterscurrentParameter = new List<string>StringBuilder();
 

            // separate parameters to escape quotes
           void tryinsertParameter()
            {
                Queue<char>var qtemp = new Queue<char>currentParameter.ToString().Trim();
 
                foreachif (var c in curlCommandstring.ToCharArrayIsNullOrEmpty(temp) == false)
                {
                    qparameters.EnqueueAdd(ctemp);
                }

                StringBuilder currentParameter = new StringBuilder.Clear();
            }

            while (true)
   void insertParameter        {
                if (q.Count == 0)
                {
                    var temp = currentParameter.ToString().Trim();
                    if (string.IsNullOrEmpty(temp) == false)
                    {
                        parameters.AddinsertParameter(temp);
                    }

                    currentParameter.Clear();break;
                }

                while (true)
                {
                  char x if= (q.Count == 0)
                    {
                        insertParameterDequeue();
                        break;
                    }

                if (x == '\'')
 char x = q.Dequeue            {
                    insertParameter();

                    if// (xadd ==until '\''we find last '
                    while (true)
                    {
                        insertParameterx = q.Dequeue();

                        // addif untilnext we2 findcharacetrs lastare '\' 
                        whileif (truex == '\\' && q.Count > 0 && q.Peek() == '\'')
                        {
                            x = q.Dequeue();

                            // if next 2 characetrs are \' 
                            if (x == '\\' && q.Count > 0 && q.Peek() == '\'')
                            {
                                currentParameter.Append('\'');
                                q.Dequeue();
                                continue;
                            }

                            if (x == '\'')
                            {
                                insertParameter();
                                break;
                            }

                            currentParameter.Append(x);
                        }
                    }
                    else if (x == '"')
                    {
                        insertParameter();

                        // add until we find last "
                      if (x while== (true'\'')
                        {
                            x = q.Dequeue();

                            // if next 2 characetrs are \"
                            if (x == '\\' && q.Count > 0 && q.Peek() == '"')
                            {
                                currentParameter.Append('"');
                                q.Dequeue();
                                continue;
                            }

                            if (x == '"')
                            {
                                insertParameter();
                                break;
                            }

                            currentParameter.Append(x);
                        }
                    }
                    else
                    {
                        currentParameter.Append(x);
                    }
                }
            }
            catch
        else if (x == {'"')
                if (Debugger.IsAttached) { Debugger.Break(); }
                throw new Exception("Invalid curl command"insertParameter();
            }

            StringBuilder finalCommand = new StringBuilder    // add until we find last "
                    while (true)
                    {
                        x = q.Dequeue();

            foreach (var p in parameters)
        // if next 2 {characetrs are \"
                        if (px == '\\' && q.StartsWithCount > 0 && q.Peek("-") == '"')
                        {
                    finalCommand        currentParameter.Append(p'"');
                    finalCommand        q.AppendDequeue(" ");
                            continue;
                        }

                var temp = p;     if (x == '"')
                        {
                            insertParameter();
                            break;
                        }

                if (temp.Contains("\""))
                {currentParameter.Append(x);
                    temp = temp.Replace("\"", "\\\"");}
                }
                if (temp.Contains("'"))else
                {
                    temp = tempcurrentParameter.ReplaceAppend("'", "\\'"x);
                }
            }
        }
        catch
        {
            if (Debugger.IsAttached) { Debugger.Break(); }
            throw new Exception("Invalid curl command");
        }

        StringBuilder finalCommand = new StringBuilder();

        foreach (var p in parameters)
        {
            if (p.StartsWith("-"))
            {
                finalCommand.Append($"\"{temp}\""p);
                finalCommand.Append(" ");
                continue;
            }

            var temp = p;

            usingif (var proc = new Processtemp.Contains("\""))
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "curl.exe",
                    Argumentstemp = finalCommandtemp.ToStringReplace(),
                    UseShellExecute = false,
                    RedirectStandardOutput = true"\"",
                    RedirectStandardError = true,"\\\"");
                    CreateNoWindow = true,}
                    WorkingDirectory =if Environment(temp.SystemDirectory
                }
            }Contains("'"))
            {
                proctemp = temp.StartReplace("'", "\\'");
            }

            finalCommand.Append($"\"{temp}\"");
    proc        finalCommand.WaitForExitAppend(timeoutInSeconds*1000" ");
        }


        using (var proc = new Process
      return proc {
            StartInfo = new ProcessStartInfo
            {
                FileName = "curl.StandardOutputexe",
                Arguments = finalCommand.ReadToEndToString();,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
                WorkingDirectory = Environment.SystemDirectory
            }
        })
        {
            proc.Start();

            proc.WaitForExit(timeoutInSeconds*1000);

            return proc.StandardOutput.ReadToEnd();
        }
    }
}
    public static string ExecuteCurl(string curlCommand, int timeoutInSeconds=60)
    {
        if (string.IsNullOrEmpty(curlCommand))
            return "";

        curlCommand = curlCommand.Trim();

        // remove the curl keworkd
        if (curlCommand.StartsWith("curl"))
        {
            curlCommand = curlCommand.Substring("curl".Length).Trim();
        }

        // this code only works on windows 10 or higher
        {
            
            curlCommand = curlCommand.Replace("--compressed", "");

            // windows 10 should contain this file
            var fullPath = System.IO.Path.Combine(Environment.SystemDirectory, "curl.exe");

            if (System.IO.File.Exists(fullPath) == false)
            {
                if (Debugger.IsAttached) { Debugger.Break(); }
                throw new Exception("Windows 10 or higher is required to run this application");
            }

            // on windows ' are not supported. For example: curl 'http://ublux.com' does not work and it needs to be replaced to curl "http://ublux.com"
            List<string> parameters = new List<string>();
 

            // separate parameters to escape quotes
            try
            {
                Queue<char> q = new Queue<char>();
 
                foreach (var c in curlCommand.ToCharArray())
                {
                    q.Enqueue(c);
                }

                StringBuilder currentParameter = new StringBuilder();

                void insertParameter()
                {
                    var temp = currentParameter.ToString().Trim();
                    if (string.IsNullOrEmpty(temp) == false)
                    {
                        parameters.Add(temp);
                    }

                    currentParameter.Clear();
                }

                while (true)
                {
                    if (q.Count == 0)
                    {
                        insertParameter();
                        break;
                    }

                    char x = q.Dequeue();

                    if (x == '\'')
                    {
                        insertParameter();

                        // add until we find last '
                        while (true)
                        {
                            x = q.Dequeue();

                            // if next 2 characetrs are \' 
                            if (x == '\\' && q.Count > 0 && q.Peek() == '\'')
                            {
                                currentParameter.Append('\'');
                                q.Dequeue();
                                continue;
                            }

                            if (x == '\'')
                            {
                                insertParameter();
                                break;
                            }

                            currentParameter.Append(x);
                        }
                    }
                    else if (x == '"')
                    {
                        insertParameter();

                        // add until we find last "
                        while (true)
                        {
                            x = q.Dequeue();

                            // if next 2 characetrs are \"
                            if (x == '\\' && q.Count > 0 && q.Peek() == '"')
                            {
                                currentParameter.Append('"');
                                q.Dequeue();
                                continue;
                            }

                            if (x == '"')
                            {
                                insertParameter();
                                break;
                            }

                            currentParameter.Append(x);
                        }
                    }
                    else
                    {
                        currentParameter.Append(x);
                    }
                }
            }
            catch
            {
                if (Debugger.IsAttached) { Debugger.Break(); }
                throw new Exception("Invalid curl command");
            }

            StringBuilder finalCommand = new StringBuilder();

            foreach (var p in parameters)
            {
                if (p.StartsWith("-"))
                {
                    finalCommand.Append(p);
                    finalCommand.Append(" ");
                    continue;
                }

                var temp = p;

                if (temp.Contains("\""))
                {
                    temp = temp.Replace("\"", "\\\"");
                }
                if (temp.Contains("'"))
                {
                    temp = temp.Replace("'", "\\'");
                }

                finalCommand.Append($"\"{temp}\"");
                finalCommand.Append(" ");
            }


            using (var proc = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "curl.exe",
                    Arguments = finalCommand.ToString(),
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true,
                    WorkingDirectory = Environment.SystemDirectory
                }
            })
            {
                proc.Start();

                proc.WaitForExit(timeoutInSeconds*1000);

                return proc.StandardOutput.ReadToEnd();
            }
        }
    }
public static string ExecuteCurl(string curlCommand, int timeoutInSeconds=60)
{
    if (string.IsNullOrEmpty(curlCommand))
        return "";

    curlCommand = curlCommand.Trim();

    // remove the curl keworkd
    if (curlCommand.StartsWith("curl"))
    {
        curlCommand = curlCommand.Substring("curl".Length).Trim();
    }

    // this code only works on windows 10 or higher
    {
        
        curlCommand = curlCommand.Replace("--compressed", "");

        // windows 10 should contain this file
        var fullPath = System.IO.Path.Combine(Environment.SystemDirectory, "curl.exe");

        if (System.IO.File.Exists(fullPath) == false)
        {
            if (Debugger.IsAttached) { Debugger.Break(); }
            throw new Exception("Windows 10 or higher is required to run this application");
        }

        // on windows ' are not supported. For example: curl 'http://ublux.com' does not work and it needs to be replaced to curl "http://ublux.com"
        List<string> parameters = new List<string>();


        // separate parameters to escape quotes
        try
        {
            Queue<char> q = new Queue<char>();

            foreach (var c in curlCommand.ToCharArray())
            {
                q.Enqueue(c);
            }

            StringBuilder currentParameter = new StringBuilder();

            void insertParameter()
            {
                var temp = currentParameter.ToString().Trim();
                if (string.IsNullOrEmpty(temp) == false)
                {
                    parameters.Add(temp);
                }

                currentParameter.Clear();
            }

            while (true)
            {
                if (q.Count == 0)
                {
                    insertParameter();
                    break;
                }

                char x = q.Dequeue();

                if (x == '\'')
                {
                    insertParameter();

                    // add until we find last '
                    while (true)
                    {
                        x = q.Dequeue();

                        // if next 2 characetrs are \' 
                        if (x == '\\' && q.Count > 0 && q.Peek() == '\'')
                        {
                            currentParameter.Append('\'');
                            q.Dequeue();
                            continue;
                        }

                        if (x == '\'')
                        {
                            insertParameter();
                            break;
                        }

                        currentParameter.Append(x);
                    }
                }
                else if (x == '"')
                {
                    insertParameter();

                    // add until we find last "
                    while (true)
                    {
                        x = q.Dequeue();

                        // if next 2 characetrs are \"
                        if (x == '\\' && q.Count > 0 && q.Peek() == '"')
                        {
                            currentParameter.Append('"');
                            q.Dequeue();
                            continue;
                        }

                        if (x == '"')
                        {
                            insertParameter();
                            break;
                        }

                        currentParameter.Append(x);
                    }
                }
                else
                {
                    currentParameter.Append(x);
                }
            }
        }
        catch
        {
            if (Debugger.IsAttached) { Debugger.Break(); }
            throw new Exception("Invalid curl command");
        }

        StringBuilder finalCommand = new StringBuilder();

        foreach (var p in parameters)
        {
            if (p.StartsWith("-"))
            {
                finalCommand.Append(p);
                finalCommand.Append(" ");
                continue;
            }

            var temp = p;

            if (temp.Contains("\""))
            {
                temp = temp.Replace("\"", "\\\"");
            }
            if (temp.Contains("'"))
            {
                temp = temp.Replace("'", "\\'");
            }

            finalCommand.Append($"\"{temp}\"");
            finalCommand.Append(" ");
        }


        using (var proc = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = "curl.exe",
                Arguments = finalCommand.ToString(),
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
                WorkingDirectory = Environment.SystemDirectory
            }
        })
        {
            proc.Start();

            proc.WaitForExit(timeoutInSeconds*1000);

            return proc.StandardOutput.ReadToEnd();
        }
    }
}
added 312 characters in body
Source Link
Tono Nam
  • 36.4k
  • 86
  • 329
  • 496

For example use this code as

var output = ExecuteCurl(@"curl 'https://google.com' -H 'Accept: application/json, text/javascript, */*; q=0.01'");

If you where to run that same string agains C:\Windows\System32\curl.exe it will not work because for some reason windows does not like single quotes.

For example use this code as

var output = ExecuteCurl(@"curl 'https://google.com' -H 'Accept: application/json, text/javascript, */*; q=0.01'");

If you where to run that same string agains C:\Windows\System32\curl.exe it will not work because for some reason windows does not like single quotes.

Source Link
Tono Nam
  • 36.4k
  • 86
  • 329
  • 496

Late response but this is what I ended up doing. If you want to run your curl commands very similarly as you run them on linux and you have windows 10 or latter do this:

    public static string ExecuteCurl(string curlCommand, int timeoutInSeconds=60)
    {
        if (string.IsNullOrEmpty(curlCommand))
            return "";

        curlCommand = curlCommand.Trim();

        // remove the curl keworkd
        if (curlCommand.StartsWith("curl"))
        {
            curlCommand = curlCommand.Substring("curl".Length).Trim();
        }

        // this code only works on windows 10 or higher
        {
            
            curlCommand = curlCommand.Replace("--compressed", "");

            // windows 10 should contain this file
            var fullPath = System.IO.Path.Combine(Environment.SystemDirectory, "curl.exe");

            if (System.IO.File.Exists(fullPath) == false)
            {
                if (Debugger.IsAttached) { Debugger.Break(); }
                throw new Exception("Windows 10 or higher is required to run this application");
            }

            // on windows ' are not supported. For example: curl 'http://ublux.com' does not work and it needs to be replaced to curl "http://ublux.com"
            List<string> parameters = new List<string>();


            // separate parameters to escape quotes
            try
            {
                Queue<char> q = new Queue<char>();

                foreach (var c in curlCommand.ToCharArray())
                {
                    q.Enqueue(c);
                }

                StringBuilder currentParameter = new StringBuilder();

                void insertParameter()
                {
                    var temp = currentParameter.ToString().Trim();
                    if (string.IsNullOrEmpty(temp) == false)
                    {
                        parameters.Add(temp);
                    }

                    currentParameter.Clear();
                }

                while (true)
                {
                    if (q.Count == 0)
                    {
                        insertParameter();
                        break;
                    }

                    char x = q.Dequeue();

                    if (x == '\'')
                    {
                        insertParameter();

                        // add until we find last '
                        while (true)
                        {
                            x = q.Dequeue();

                            // if next 2 characetrs are \' 
                            if (x == '\\' && q.Count > 0 && q.Peek() == '\'')
                            {
                                currentParameter.Append('\'');
                                q.Dequeue();
                                continue;
                            }

                            if (x == '\'')
                            {
                                insertParameter();
                                break;
                            }

                            currentParameter.Append(x);
                        }
                    }
                    else if (x == '"')
                    {
                        insertParameter();

                        // add until we find last "
                        while (true)
                        {
                            x = q.Dequeue();

                            // if next 2 characetrs are \"
                            if (x == '\\' && q.Count > 0 && q.Peek() == '"')
                            {
                                currentParameter.Append('"');
                                q.Dequeue();
                                continue;
                            }

                            if (x == '"')
                            {
                                insertParameter();
                                break;
                            }

                            currentParameter.Append(x);
                        }
                    }
                    else
                    {
                        currentParameter.Append(x);
                    }
                }
            }
            catch
            {
                if (Debugger.IsAttached) { Debugger.Break(); }
                throw new Exception("Invalid curl command");
            }

            StringBuilder finalCommand = new StringBuilder();

            foreach (var p in parameters)
            {
                if (p.StartsWith("-"))
                {
                    finalCommand.Append(p);
                    finalCommand.Append(" ");
                    continue;
                }

                var temp = p;

                if (temp.Contains("\""))
                {
                    temp = temp.Replace("\"", "\\\"");
                }
                if (temp.Contains("'"))
                {
                    temp = temp.Replace("'", "\\'");
                }

                finalCommand.Append($"\"{temp}\"");
                finalCommand.Append(" ");
            }


            using (var proc = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "curl.exe",
                    Arguments = finalCommand.ToString(),
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true,
                    WorkingDirectory = Environment.SystemDirectory
                }
            })
            {
                proc.Start();

                proc.WaitForExit(timeoutInSeconds*1000);

                return proc.StandardOutput.ReadToEnd();
            }
        }
    }

The reason why the code is a little bit long is because windows will give you an error if you execute a single quote. In other words, the command curl 'https://google.com' will work on linux and it will not work on windows. Thanks to that method I created you can use single quotes and run your curl commands exactly as you run them on linux. This code also checks for escaping characters such as \' and \".