I have a async void function that I call to execute a couple curl calls. I have code that needs to execute after that function is executed as a variable is set inside the function. Right now it looks like the code is executed before the async function. Any suggestions?
Update(allNumbers, allValues);
//result is a global variable that is set inside the Update function.
if (result.Contains("success"))
{
message.InnerText = "Result: " + result + "\r\nSuccessfully updated value";
}
else
{
message.InnerText = "Result: " + result + "\r\nError updating value";
}
async void Update(List<string> allNumbers, List<string> allValues){
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
string file = "";
HttpRequestMessage response = new HttpRequestMessage();
using (var client = new HttpClient(handler))
{
client.Timeout = TimeSpan.FromMinutes(30);
client.BaseAddress = new Uri('Web IP');
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
try
{
file = System.IO.File.ReadAllText(path + "user.xml");
response = new HttpRequestMessage(HttpMethod.Post, 'Web Extension 1');
response.Content = new StringContent(file, Encoding.UTF8, "application/xml");
await client.SendAsync(response).ContinueWith(responseTask =>
{
Uri uri = new Uri('Web IP' + 'Web Extension 1');
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
foreach (Cookie the_cookie in responseCookies)
{
File.WriteAllText(path + "sessionid.txt", String.Empty);
using (var tw = new StreamWriter(path + "sessionid.txt", true))
{
// Create file with cookie information
}
}
});
}
catch (Exception ex)
{
using (var stw = new StreamWriter(path + "error.txt", true))
{
stw.WriteLine("Error with Login cURL Call - " + ex.ToString() + "\r\n---------------------------------------------------");
}
result = "Error with Login cURL Call -" + ex.ToString();
}
string id = "";
try
{
response = new HttpRequestMessage(HttpMethod.Get, 'Web Extension 2');
await client.SendAsync(response).ContinueWith(responseTask =>
{
string contents = responseTask.Result.Content.ReadAsStringAsync().Result;
//assign id value
});
}
catch (Exception ex)
{
using (var tsw = new StreamWriter(path + "error.txt", true))
{
tsw.WriteLine("Error with Load Config cURL Call - " + ex.ToString() + "\r\n---------------------------------------------------");
}
result = "Error with Load Config cURL Call - " + ex.ToString();
}
if (id != "")
{
for (int i = 0; i < allNumbers.Count; i++)
{
try
{
file = System.IO.File.ReadAllText(path + allNumbers[i] + ".xml");
response = new HttpRequestMessage(HttpMethod.Post, 'We Extension 3.1' + id + 'Web Extension 3.2');
response.Content = new StringContent(file, Encoding.UTF8, "application/xml");
await client.SendAsync(response).ContinueWith(responseTask =>
{
});
}
catch (Exception ex)
{
using (var stw = new StreamWriter(path + "error.txt", true))
{
stw.WriteLine("Error with Update cURL Call - " + ex.ToString() + "\r\n---------------------------------------------------");
}
result = "Error with Update cURL Call - " + ex.ToString();
}
try
{
file = System.IO.File.ReadAllText(path + "saveActivate.xml");
response = new HttpRequestMessage(HttpMethod.Post, 'Web Extension 4.1' + id + 'Web Extension 4.1');
response.Content = new StringContent(file, Encoding.UTF8, "application/xml");
await client.SendAsync(response).ContinueWith(responseTask =>
{
});
}
catch (Exception ex)
{
using (var stw = new StreamWriter(path + "error.txt", true))
{
stw.WriteLine("Error with Save and Activate cURL Call - " + ex.ToString() + "\r\n---------------------------------------------------");
}
result = "Error with Save and Activate cURL Call - " + ex.ToString();
}
try
{
response = new HttpRequestMessage(HttpMethod.Get, 'Web Extension 5.1' + id + 'Web Extension 5.2');
await client.SendAsync(response).ContinueWith(responseTask =>
{
result = "Value update was a success!";
});
}
catch (Exception ex)
{
using (var stw = new StreamWriter(path + "error.txt", true))
{
stw.WriteLine("Error with Load Config cURL Call - " + ex.ToString() + "\r\n---------------------------------------------------");
}
result = "Error with Load Config cURL Call - " + ex.ToString();
}
}
}
else
{
using (var tsw = new StreamWriter(path + "error.txt", true))
{
tsw.WriteLine("Error getting current SDM ID number.\r\n---------------------------------------------------");
}
result = "Error getting current SDM ID number.";
}
}
}
Here is the updated code for the Update() function.
Change your async method to return a Task and then in your main method call await (your async method):
public async Task<T> Update(List<string> allNumbers, List<string> allValues)
In the Main method
await Update(allNumbers, allValues);
Related
I want to translate a given string to a specific language and print the translation to console , but my console prints nothing , I am also trying to catch some error , but my console still prints nothing, anyone know why ?
Here are my headers:
using Newtonsoft.Json;
using System.Net.Http;
using NPOI.SS.Formula.Functions;
I have defined the necessary key and region and url attribute inside class block , but it just won't work like this :
public const string subscriptionKey = "mykey";
public const string region = "myregion";
public const string endpoint="https://api.cognitive.microsofttranslator.com/";
mykey consists of my subscription key and myregion consists of my region
Here is my main:
TranslateString();
Here is my implementation of method TranslateString
public static async void TranslateString()
{
string route = "translate?api-version=3.0&from=en&to=fr&to=zu";
string xmlString = "Hello , welcome";
try
{
object[] body = new object[] { new { Text = xmlString } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
request.Headers.Add("Ocp-Apim-Subscription-Region", region);
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success , translated text:");
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
else
{
Console.WriteLine("Error: " + response.StatusCode + " " + response.ReasonPhrase);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.Message);
}
Here is your code with minimal changes to make it produce an output. The relevant change is for TranslateString() to return a Task, so that the main thread waits for the async call to complete. Another option would have been to make this a synchronous call.
This uses the .Net built-in Json serializer instead of Newtonsoft for simplicity.
This compiles as is using .Net7 with C#10, and your key and region filled in.
using System.Net;
using System.Text;
using System.Text.Json;
const string subscriptionKey = "mykey";
const string region = "myregion";
const string endpoint = "https://api.cognitive.microsofttranslator.com/";
Console.WriteLine("Program Start");
await TranslateString();
static async Task TranslateString()
{
string route = "translate?api-version=3.0&from=en&to=fr&to=zu";
string xmlString = "Hello , welcome";
try
{
object[] body = new object[] { new { Text = xmlString } };
var requestBody = JsonSerializer.Serialize(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
request.Headers.Add("Ocp-Apim-Subscription-Region", region);
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success , translated text:");
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
else
{
Console.WriteLine("Error: " + response.StatusCode + " " + response.ReasonPhrase);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.Message);
}
}
The output is:
Program Start
Success , translated text:
[{"translations":[{"text":"Bonjour , bienvenue","to":"fr"},{"text":"Sawu , wamukelekile","to":"zu"}]}]
You will need to add deserializing the output.
I want to translate single document from one language to another please guide me how to do that i have done translating all the files in azure blob storage but not able to find to translate single file.
please find below code and let me know the changes.
string _FileName = Path.GetFileName(file.FileName);
fileName = _FileName;
string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);
file.SaveAs(_path);
string route = "/batches";
string endpoint = "https://translator.cognitiveservices.azure.com/translator/text/batch/v1.0";
string filePath = UploadToAzureStorageAccount.UploadDocument(_path, "uploadeddocs");
string subscriptionKey = "key";
string json = ("" +
"{\"inputs\": " +
"[{\"storageType\": \"File\","+"\"source\": " +
"{\"sourceUrl\": \"https://cdposticketsstorage.blob.core.windows.net/uploadeddocs/test.docx?sp=r&st=2022-03-08T08:13:18Z&se=2022-03-08T16:13:18Z&spr=https&sv=2020-08-04&sr=b&sig=Pt68ogFCj6WSgEBUWI95YJ4GudOcyhEW1cgVXmFCing%3D\"," +
"\"storageSource\": \"AzureBlob\"" +
"}," +
"\"targets\": " +
"[{\"targetUrl\": \"https://cdposticketsstorage.blob.core.windows.net/translateddocs/translate.docx?sp=rcw&st=2022-03-08T11:15:45Z&se=2022-03-08T19:15:45Z&spr=https&sv=2020-08-04&sr=b&sig=QM2FhLxOIE%2FLjeLLfYyR2PmfkNb3nm70wZdCveSJC0M%3D\"," +
"\"storageSource\": \"AzureBlob\"," +
"\"language\": \"fr\"}]}]}");
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
string result = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Status code: {response.StatusCode}");
Console.WriteLine();
Console.WriteLine($"Response Headers:");
Console.WriteLine(response.Headers);
}
else
Console.Write("Error");
}
// TextTranslatorAPI client = new TextTranslatorAPI();
//string res = await client.DocumentTranslator(fileName);
//return res;
}
ViewBag.Message = "File Uploaded Successfully!!";
}
catch(Exception e)
{
ViewBag.Message = "File upload failed!!";
}
We have a POST method in the the Microsoft .NET Web API. That post method processes PDF file into a Sharepoint Site. We did test this method in Postman, and this method works accordingly
However, we are trying to execute this method via the submit button on the PDF itself with the action URL specific for the Post method in the Web Api, the very same URL that properly works in the postman
When I try to execute that action/clicking the Submit button, I get a following error
Is there any specific strategy to execute the Web Api POST method directly through the PDF submit button
Thank you in advance
Here is my Web Api Post method
[HttpPost]
[Route("SubmitForm")]
public async Task<IActionResult> SubmitForm()
{
var file = Request.Form.Files[0];
HttpClient client = GetBinaryRequestClient();
try
{
byte[] docAsBytes;
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
docAsBytes = ms.ToArray();
}
PdfReader pdfReader = new PdfReader(docAsBytes);
MemoryStream m = new MemoryStream();
PdfStamper outStamper = new PdfStamper(pdfReader,m);
string formName = outStamper.AcroFields.GetField("FormSeqNo");
string endpointUrl = string.Format(
"{0}{1}/_api/web/GetFolderByServerRelativeUrl('{2}')/Files/Add(url='{3}', overwrite=true)",
this.apiService.AppSettings.SharePointSettings.SPSiteURL,
this.apiService.AppSettings.SharePointSettings.SmartFormsRelativeSiteURL,
this.apiService.AppSettings.SharePointSettings.SubmittedPDFsLibrary,
$"{formName}.pdf");
ByteArrayContent imageBytes = new ByteArrayContent(docAsBytes);
var result = await client.PostAsync(endpointUrl, imageBytes);
return Ok();
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, $"Error in method {ex.Message}");
}
}
Here is the answer that works for me. The .NET API method has to properly receive PDF based requests and write the responses back with the DFD type, NOT return it
[HttpPost]
[Route("SubmitForm")]
public async Task SubmitForm()
{
var file = Request.Body;
HttpClient client = GetBinaryRequestClient();
try
{
byte[] docAsBytes;
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
docAsBytes = ms.ToArray();
}
PdfReader pdfReader = new PdfReader(docAsBytes);
MemoryStream m = new MemoryStream();
PdfStamper outStamper = new PdfStamper(pdfReader,m);
string formName = outStamper.AcroFields.GetField("FormSeqNo");
string endpointUrl = string.Format(
"{0}{1}/_api/web/GetFolderByServerRelativeUrl('{2}')/Files/Add(url='{3}', overwrite=true)",
this.apiService.AppSettings.SharePointSettings.SPSiteURL,
this.apiService.AppSettings.SharePointSettings.SmartFormsRelativeSiteURL,
this.apiService.AppSettings.SharePointSettings.SubmittedPDFsLibrary,
$"{formName}.pdf");
ByteArrayContent imageBytes = new ByteArrayContent(docAsBytes);
var result = await client.PostAsync(endpointUrl, imageBytes);
Response.Redirect(this.apiService.AppSettings.SharePointSettings.SPSiteURL);
//return Ok();
}
catch (Exception ex)
{
//return null;// StatusCode(StatusCodes.Status500InternalServerError, $"Error in method {ex.Message}");
await ReturnFDFResponse("Error Occured " + ex.Message);
}
}
private async Task ReturnFDFResponse(string status)
{
string fdfmessage = "%FDF-1.2" + "\n" + "1 0 obj <<" + "\n" + "/FDF <<" +
"\n" + "/Status (" + status + "!)" + "\n" + ">>" + "\n" +
">>" + "\n" + "endobj" + "\n" + "trailer" + "\n" + "<</Root 1 0 R>>" +
"\n" + "%%EOF";
HttpResponseMessage fdfresult = new HttpResponseMessage(HttpStatusCode.OK);
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(fdfmessage));
stream.Position = 0;
fdfresult.Content = new StreamContent(stream);
fdfresult.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.fdf");
Response.ContentType = "application/vnd.fdf";
await Response.Body.WriteAsync(stream.ToArray());
}
I am fairly new to programming. I require exception handling for my HttpWebRequest to an Api. Below is my code, I haven't done error handling before so just an example of how to accomplish this will be appreciated.
private void button1_Click(object sender, EventArgs e)
{
Class1.PostDevices x = new Class1.PostDevices();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webAddr);
request.ContentType = "application/json";
request.Method = "POST";
request.Timeout = 5000;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string jsonstring;
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Class1.PostDevices));
x.notification = new Class1.Notification();
x.profile = "dev";
x.notification.message = "Hello World";
ser.WriteObject(stream1, x);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
jsonstring = sr.ReadToEnd();
Debug.WriteLine(JObject.Parse(jsonstring));
streamWriter.Write(jsonstring);
streamWriter.Flush();
}
HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Debug.WriteLine(JObject.Parse(result));
Reponse.PostDevicesReponse MyResult = JsonConvert.DeserializeObject<Reponse.PostDevicesReponse>(result);
}
}
}
}
1) Create a folder named as "ExceptionTextFile" inside your application
2) Create a Separate Class like below to log the exception
using System;
using System.IO;
using context = System.Web.HttpContext;
//Define your application namespace here
namespace YourApplicationNamespace
{
public static class ExceptionLogging
{
private static String ErrorlineNo, Errormsg, extype, exurl, ErrorLocation;
public static void SendErrorToText(Exception ex)
{
var line = Environment.NewLine + Environment.NewLine;
ErrorlineNo = ex.StackTrace.ToString();
Errormsg = ex.Message;
extype = ex.GetType().ToString();
exurl = context.Current.Request.Url.ToString();
ErrorLocation = ex.Message.ToString();
try
{
//Create a folder named as "ExceptionTextFile" inside your application
//Text File Path
string filepath = context.Current.Server.MapPath("~/ExceptionTextFile/");
if (!Directory.Exists(filepath))
{
Directory.CreateDirectory(filepath);
}
//Text File Name
filepath = filepath + DateTime.Today.ToString("dd-MM-yy") + ".txt";
if (!File.Exists(filepath))
{
File.Create(filepath).Dispose();
}
using (StreamWriter sw = File.AppendText(filepath))
{
string error = "Log Written Date:" + " " + DateTime.Now.ToString()
+ line + "Error Line No :" + " " + ErrorlineNo + line
+ "Error Message:" + " " + Errormsg + line + "Exception Type:" + " "
+ extype + line + "Error Location :" + " " + ErrorLocation + line
+ " Error Page Url:" + " " + exurl + line + line;
sw.WriteLine("-----------Exception Details on " + " " + DateTime.Now.ToString() + "-----------------");
sw.WriteLine("-------------------------------------------------------------------------------------");
sw.WriteLine(line);
sw.WriteLine(error);
sw.WriteLine("--------------------------------*End*------------------------------------------");
sw.WriteLine(line);
sw.Flush();
sw.Close();
}
}
catch (Exception e)
{
e.ToString();
}
}
}
}
After that inside your button click event define try...catch block and log the exception like below
private void button1_Click(object sender, EventArgs e)
{
try
{
Class1.PostDevices x = new Class1.PostDevices();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webAddr);
request.ContentType = "application/json";
request.Method = "POST";
request.Timeout = 5000;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string jsonstring;
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Class1.PostDevices));
x.notification = new Class1.Notification();
x.profile = "dev";
x.notification.message = "Hello World";
ser.WriteObject(stream1, x);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
jsonstring = sr.ReadToEnd();
Debug.WriteLine(JObject.Parse(jsonstring));
streamWriter.Write(jsonstring);
streamWriter.Flush();
}
HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Debug.WriteLine(JObject.Parse(result));
Reponse.PostDevicesReponse MyResult = JsonConvert.DeserializeObject<Reponse.PostDevicesReponse>(result);
}
}
}
}
catch (Exception e)
{
ExceptionLogging.SendErrorToText(e);
}
}
If any error appears go to the "ExceptionTextFile" folder and check the log. The exception would be logged there.
Try and revert me back if this solves your problem or not
Im trying out the Convertapi in a Windows store App project, and i want to send a .docx file and get a pdf file in return, im trying to do a post but im not sure how its done, this is what i have so far, but its not working.
private async Task GeneratePdfContract(string path) {
try {
var data = new List < KeyValuePair < string, string >> {
new KeyValuePair < string, string > ("Api", "5"),
new KeyValuePair < string, string > ("ApiKey", "419595049"),
new KeyValuePair < string, string > ("File", "" + stream2),
};
await PostKeyValueData(data);
} catch (Exception e) {
Debug.WriteLine(e.Message);
}
}
private async Task PostKeyValueData(List < KeyValuePair < string, string >> values) {
var httpClient = new HttpClient();
var response = await httpClient.PostAsync("http://do.convertapi.com/Word2Pdf", new FormUrlEncodedContent(values));
var responseString = await response.Content.ReadAsStringAsync();
}
How should i do my post to send a .docx file and get a .pdf file in return?
Edit:
private async Task GeneratePdfContract(string path)
{
try
{
using (var client = new System.Net.Http.HttpClient())
{
using (var multipartFormDataContent = new MultipartFormDataContent())
{
var values = new[]
{
new KeyValuePair<string, string>("ApiKey", "413595149")
};
foreach (var keyValuePair in values)
{
multipartFormDataContent.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key));
}
StorageFolder currentFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(Constants.DataDirectory);
StorageFile outputFile = await currentFolder.GetFileAsync("file.docx");
byte[] fileBytes = await outputFile.ToBytes();
//multipartFormDataContent.Add(new ByteArrayContent(FileIO.ReadBufferAsync(#"C:\test.docx")), '"' + "File" + '"', '"' + "test.docx" + '"');
multipartFormDataContent.Add(new ByteArrayContent(fileBytes));
const string requestUri = "http://do.convertapi.com/word2pdf";
var response = await client.PostAsync(requestUri, multipartFormDataContent);
if (response.IsSuccessStatusCode)
{
var responseHeaders = response.Headers;
var paths = responseHeaders.GetValues("OutputFileName").First();
var path2 = Path.Combine(#"C:\", paths);
StorageFile sampleFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(#"C:\Users\Thought\AppData\Local\Packages\xxxxx_apk0zz032bzya\LocalState\Data\");
await FileIO.WriteBytesAsync(sampleFile, await response.Content.ReadAsByteArrayAsync());
}
else
{
Debug.WriteLine("Status Code : {0}", response.StatusCode);
Debug.WriteLine("Status Description : {0}", response.ReasonPhrase);
}
}
}
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
}
#Tomas tried to adapt your answer a bit since there doesn't seem to be a "File.ReadAllBytes" on windows store apps, im getting this response tho :\
You can't pass file stream as string to HttpClient. Just use WebClient.UploadFile method which also support asynchronous uploads.
using (var client = new WebClient())
{
var fileToConvert = "c:\file-to-convert.docx";
var data = new NameValueCollection();
data.Add("ApiKey", "413595149");
try
{
client.QueryString.Add(data);
var response = client.UploadFile("http://do.convertapi.com/word2pdf", fileToConvert);
var responseHeaders = client.ResponseHeaders;
var path = Path.Combine(#"C:\", responseHeaders["OutputFileName"]);
File.WriteAllBytes(path, response);
Console.WriteLine("The conversion was successful! The word file {0} converted to PDF and saved at {1}", fileToConvert, path);
}
catch (WebException e)
{
Console.WriteLine("Exception Message :" + e.Message);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
}
}
}
The example using HttpClient()
using (var client = new System.Net.Http.HttpClient())
{
using (var multipartFormDataContent = new MultipartFormDataContent())
{
var values = new[]
{
new KeyValuePair<string, string>("ApiKey", "YourApiKey")
};
foreach (var keyValuePair in values)
{
multipartFormDataContent.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key));
}
multipartFormDataContent.Add(new ByteArrayContent(File.ReadAllBytes(#"C:\test.docx")), '"' + "File" + '"', '"' + "test.docx" + '"');
const string requestUri = "http://do.convertapi.com/word2pdf";
var response = await client.PostAsync(requestUri, multipartFormDataContent);
if (response.IsSuccessStatusCode)
{
var responseHeaders = response.Headers;
var paths = responseHeaders.GetValues("OutputFileName").First();
var path = Path.Combine(#"C:\", paths);
File.WriteAllBytes(path, await response.Content.ReadAsByteArrayAsync());
}
else
{
Console.WriteLine("Status Code : {0}", response.StatusCode);
Console.WriteLine("Status Description : {0}", response.ReasonPhrase);
}
}
}