3

I have a curl script that downloads a file. How do I convert this to C#?

Dim strCurl1 
Dim strCurl2 
Dim strCurl3 
Dim strCurl4 

strCurl1 = "c:\temp\Curl\curl -d "
strCurl2 = "username=myUser&password=passwrd&asof=" & fileName & "&format=csv"
strCurl3 = "https://website/PresentValueServlet > " & "c:\temp\Curl\Results_" & fileName & ".csv"
strCurl4 = strCurl1 & Chr(34) & strCurl2 & Chr(34) & " " & strCurl3 & " --insecure  --proxy proxy.myserver.com:8080 --proxy-user admin:passAdmin"

Set objShell = CreateObject("WScript.Shell")
objShell.run "cmd /K " & strCurl4

My C# to date...

string username = "myUser";
string password = "passwrd";
string fileDestination = @"c:\temp\Curl\Results_" + fileName + ".csv";
using (WebClient client = new WebClient())
{
   client.Credentials = new NetworkCredential(username, password);
   client.DownloadFile(string.Format("https://website/PresentValueServlet"), fileDestination);
}

Updated C# code with Proxy...

WebProxy proxy = new WebProxy("myurl:8080", true);
proxy.Credentials = new NetworkCredential("admin", "pswrd");
client.Proxy = proxy;

Error: The remote server returned an error: (403) Forbidden.

1 Answer 1

1

Use one of the following options:

HttpWebRequest/HttpWebResponse WebClient HttpClient (available from .NET 4.5 on)

I'd highly recommend using the HttpClient class, as it's engineered to be much better (from a usability standpoint) than the former two.

In your case, you would do this:

using System.Net.Http;

var client = new HttpClient();

// Create the HttpContent for the form to be posted.
var requestContent = new FormUrlEncodedContent(new [] {
new KeyValuePair<string,>("text", "This is a block of text"),
});

// Get the response.
HttpResponseMessage response = await client.PostAsync(
"http://api.repustate.com/v2/demokey/score.json",
requestContent);

// Get the response content.
HttpContent responseContent = response.Content;

// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
// Write the output.
Console.WriteLine(await reader.ReadToEndAsync());
}

this answer is from this site.

Another refference i found this solution in the net.

You can also try and look in this answer.

Sign up to request clarification or add additional context in comments.

1 Comment

It works on a server that does not need a proxy. The curl script that works uses... strCurl4 = strCurl1 & Chr(34) & strCurl2 & Chr(34) & " " & strCurl3 & " --insecure --proxy muurl:8080 --proxy-user admin:pswrd" My C# code is updated in original post. Only difference looks to be use of insecure in the curl script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.