Hello locherlav,
I believe that this code you are working on is a conversion of an existing code to create a bulk upload fom VB.NET to C#. During the conversion process, several important parts of the multipart request were broken. I have taken the time to correct the code and you should see success with the code below. Please take a moment to read the comments in the code, as they are relevant to having it work properly.
Code:
HttpWebRequest httpclient = (HttpWebRequest)WebRequest.Create("https://api.constantcontact.com/v2/activities/addcontacts?api_key=wv7crkj3rk3gy52ykqegkxqq");
string boundary = "--" + Guid.NewGuid().ToString();
string filename = "F:\\constant contact Wrapper\\Constant.csv";
httpclient.Headers.Add("Authorization", "Bearer 2269f201-044b-45f7-8015-e5e107555dd5");
httpclient.Method = "POST";
httpclient.ContentType = string.Format("multipart/form-data");
httpclient.Accept = "application/json";
httpclient.PreAuthenticate = true;
StringBuilder sb= new StringBuilder();
sb.AppendLine(boundary);
sb.AppendLine("content-disposition: form-data; name=\"file_name\"");
sb.AppendLine();
sb.AppendLine("Constant.csv"); // filename
sb.AppendLine(boundary);
sb.AppendLine("content-disposition: form-data; name=\"lists\"");
sb.AppendLine();
sb.AppendLine("1"); // Constant Contact List ID Number
sb.AppendLine(boundary);
sb.AppendLine("content-disposition: file; name=\"data\" filename=\"emailkust.csv\"");
sb.AppendLine("Content-Type: text/csv");
sb.AppendLine();
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
byte[] contents = new byte[fs.Length];
fs.Read(contents, 0, contents.Length);
sb.Append(Encoding.Default.GetString(contents));
}
sb.AppendLine(boundary + "--");
byte[] fulldata = Encoding.Default.GetBytes(sb.ToString());
using (Stream sw = httpclient.GetRequestStream()) {
sw.Write(fulldata, 0, fulldata.Length);
}
try {
HttpWebResponse response = httpclient.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(response.GetResponseStream())) {
// add code here to display the contents from sr.ReadToEnd() to see the response from ther server
}
} catch (WebException ex) {
using (StreamReader sr = new StreamReader(ex.Response.GetResponseStream())) {
// add code here to display the contents from sr.ReadToEnd() to see the response from ther server
// add code here to display e.Message to see a shorter error message
}
}
If you are still having problems, please post the detailed error message here so that I can assist you.
Best Regards,
... View more