Reputation: 49
I am trying to curl file contents to an external source. I can curl it correctly from the command line, but I am having problem sending the string in the -d switch in code. Here is the gist of the curl command
curl.exe -u userName:password -H "Content-Type: text/plain" -X PUT https://someIp/command?filename=filename.txt -d "content of filename.text is here" --insecure
I can send the file, and they receive it on the other end, the problem is that the content of the file isn't making it over to them. Does anyone have any experience or ideas here? Here is the code from my proof of concept.
ServicePointManager.ServerCertificateValidationCallback = new
System.Net.Security.RemoteCertificateValidationCallback
(
delegate { return true; }
);
// create the requst address to send the file to
string requestAddress = string.Format("{0}{1}", this.CurlAddress, Path.GetFileName(fileName));
// spin up the request object, set neccessary paramaters
var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(requestAddress);
request.ContentType = "text/plain";
request.Method = "PUT";
request.Credentials = new NetworkCredential("userName", "password");
// open the web request stream
using (var stream = request.GetRequestStream())
{
// create a writer to the request stream
using (var writer = new StringWriter())
{
// write the text to the stream
writer.Write(File.ReadAllLines(fileName));
stream.Close();
}
}
// Get the response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
Console.WriteLine(string.Format("Response: {0}", responseString));
}
Upvotes: 0
Views: 3294
Reputation: 49
The problem was that I wasn't writing the file contents to the stream from the requests .GetRequestStream(). Once I wrote the contents there, it appeared on the other end. New stripped down code is
// open the web request stream
using (var stream = request.GetRequestStream())
{
byte[] file = File.ReadAllBytes(fileName);
stream.Write(file, 0, file.Length);
stream.Close();
}
Upvotes: 1
Reputation: 7091
I think what you're after is Put
with string content. This can easily be done asynchronously with an HttpClient
.
private static HttpClient client = new HttpClient();
private async Task CurlFileContents(Uri uri, string contents)
{
var content = new StringContent(contents, Encoding.Default, "text/plain");
var repsonse = await client.PutAsync(uri, content);
var responseContent = await repsonse.Content.ReadAsStringAsync();
//operate on response
}
Upvotes: 0