public static MimeMultipartStream FromContent(IDictionary <string, object> content) { var boundary = $"----------{DateTime.Now.Ticks.ToString("x")}"; var ms = new MimeMultipartStream { ContentType = $"multipart/form-data; boundary={boundary}" }; var header = $"--{boundary}{Environment.NewLine}"; var footer = $"{Environment.NewLine}--{boundary}--{Environment.NewLine}"; var addCRLF = false; var keys = (content ?? new Dictionary <string, object>()).Keys; foreach (string key in keys) { if (addCRLF) { WriteToStream(ms, Environment.NewLine); } var value = content[key] ?? string.Empty; var bs = value as BlobStream; if (bs != null) { WriteToStream(ms, header); WriteToStream(ms, $"Content-Disposition: form-data; name=\"{key}\"; filename=\"{bs.FileName ?? key}\"{Environment.NewLine}"); WriteToStream(ms, $"Content-Type: {bs.ContentType ?? "application/octet-stream"}{Environment.NewLine}{Environment.NewLine}"); WriteToStream(ms, bs.Buffer); continue; } WriteToStream(ms, header); WriteToStream(ms, $"Content-Disposition: form-data; name=\"{key}\"{Environment.NewLine}{Environment.NewLine}"); WriteToStream(ms, value.ToString()); addCRLF = true; } WriteToStream(ms, footer); return(ms); }
static void Import(string token, string importdir, List <KeyValuePair <string, byte[]> > files) { string apiUrl = config["apiUrl"]; if (Directory.Exists(importdir)) { files.Clear(); foreach (var filepath in Directory.GetFiles(importdir, "*.csetw", SearchOption.AllDirectories)) { var buffer = File.ReadAllBytes(filepath); files.Add(new KeyValuePair <string, byte[]>(Path.GetFileName(filepath), buffer)); } } var req = new WebRequestOptions { UriString = $"{apiUrl}{Urls.import}", Headers = new Dictionary <string, string> { { "Authorization", token } } }; foreach (var file in files) { var filename = file.Key; var buffer = file.Value; using (var bs = new BlobStream(filename, "application/octet-stream")) { bs.Write(buffer, 0, buffer.Length); var content = new Dictionary <string, object> { { "file", bs } }; using (var data = MimeMultipartStream.FromContent(content)) { try { var resp = req.Post(new HttpPostPayload { ContentType = data.ContentType, Data = data.Buffer }); var log = $"{filename} | {resp}"; Console.WriteLine(log); Log.Information(log); } catch (WebException ex) { using (var stream = ex.Response.GetResponseStream()) { using (var reader = new StreamReader(stream)) { var json = reader.ReadToEnd(); var err = JObject.Parse(json); var log = $"{filename} | \"Failed to import assessment\""; Console.WriteLine(log); Log.Error(ex, log); Log.Error("Server-Message: {0}", err.Value <string>("Message")); Log.Error("Server-ExceptionType: {0}", err.Value <string>("ExceptionType")); Log.Error("Server-ExceptionMessage: {0}", err.Value <string>("ExceptionMessage")); Log.Error("Server-StackTrace: {0}", err.Value <string>("StackTrace")); } } } } } } }