我正在尝试将文件内容卷曲到外部源。我可以从命令行正确卷曲它,但我在代码中的-d开关中发送字符串时遇到问题。这是curl命令的要点
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
我可以发送文件,并且他们在另一端收到它,问题是文件的内容没有交给他们。有没有人有这方面的经验或想法?这是我的概念证明的代码。
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));
}
答案 0 :(得分:1)
问题在于我没有从请求.GetRequestStream()中将文件内容写入流中。一旦我在那里写了内容,就会出现在另一端。新的精简代码是
// open the web request stream
using (var stream = request.GetRequestStream())
{
byte[] file = File.ReadAllBytes(fileName);
stream.Write(file, 0, file.Length);
stream.Close();
}
答案 1 :(得分:0)
我认为你所追求的是Put
字符串内容。这可以使用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
}