How to upload any file on Slack via Slack-App in c#











up vote
1
down vote

favorite












I need help with uploading files to Slack.



I have a Slack-App that is working with my code(below) so far. But all I can do is post messages. I can not attach images to the messages - because I do not understand how to use the so called "methods" and the syntax Slack is "showing" on their API-page.



This creates my "content" and below its just a Stream for reading a file I could upload:



    public class PostMessage
{


public FormUrlEncodedContent Content(string message, string file)
{
var values = new Dictionary<string, string>
{
{"token", "xoxp-myToken"},
{ "username", "X"},
{ "channel", "myChannel"},
{ "as_user", "false"},
{"text", message},
{ "content", file},
{ "attachments","[{ "fallback":"dummy", "text":"this is a waste of time"}]"}
};

var content = new FormUrlEncodedContent(values);

return content;
}
}

public class PostFile
{
String path = @"C:Usersf.heldDesktopHeld-Docsdagged.jpg";

public string ReadImageFile()
{
FileInfo fileInfo = new FileInfo(path);
long imageFileLength = fileInfo.Length;
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte imageData = br.ReadBytes((int)imageFileLength);
var str = Encoding.Default.GetString(imageData);
return str;
}
}
}


The client that communicates:



public class SlackClient
{
private readonly Uri _webhookUrl;
private readonly HttpClient _httpClient = new HttpClient {};

public SlackClient(Uri webhookUrl)
{
_webhookUrl = webhookUrl;
}

public async Task<HttpResponseMessage> SendMessageAsync(FormUrlEncodedContent content)
{
var response = await _httpClient.PostAsync(_webhookUrl, content);

return response;
}
}
}


The Main:



public static void Main(string args)
{
Task.WaitAll(IntegrateWithSlackAsync());
}

private static async Task IntegrateWithSlackAsync()
{
var webhookUrl = new Uri("https://slack.com/api/files.upload");
var slackClient = new SlackClient(webhookUrl);
PostMessage PM = new PostMessage();
PostFile PF = new PostFile();


while (true)
{
Console.Write("Type a message: ");
var message = Console.ReadLine();
var testFile = PF.ReadImageFile();
FormUrlEncodedContent payload = PM.Content(message, testFile);
var response = await slackClient.SendMessageAsync(payload);
var isValid = response.IsSuccessStatusCode ? "valid" : "invalid";
Console.WriteLine($"Received {isValid} response.");
Console.WriteLine(response);
response.Dispose();
}
}


}
}



If somebody has an example on what a upload has to look like. Or even better,



if somebody could really explain the syntax these Slack-Messages have to have.



That would be great! I still do not know where and HOW I should put the so called
"Accepted content types: multipart/form-data, application/x-www-form-urlencoded" to my upload. I just can not find examples on this...



Edit:



What confuses me needlesly is that Slack states they have an extra method called file.upload - but we shouldn't use it anymore, we should use just postMessage.



But how would I "pack" a file in a message? My syntax always seems to be off. Especially when it comes to "content"...
I just can not figure out what the c#-code has to look like. Where do I declare the aforementioned "content type"?



Another problem is, it always sends my messages through - means I get a 200-response from the server. But it never shows the file (which probably means the syntax is off) Or I get the 200-response but the message never shows in Slack.










share|improve this question
























  • Can you please clarify what your aim is: do you want to attach an image to your message OR do you want to upload a file to Slack?
    – Erik Kalkoken
    Nov 12 at 15:06










  • Hey Erik, well I need to be able to do both. But why is there even a difference? Everything is a file, right? I know you posted on my other question that with messages I could only post images. But Slack explicitely states that file uploads are treated as messages now (look here: api.slack.com/changelog/2018-05-file-threads-soon-tread ) . Or am I reading this wrong? When I use the SlackRTM it doesn't seem to behave differently when uploading images of any kind or files... so?! Thanks!
    – Fabian Held
    Nov 12 at 15:11












  • you are correct. files.upload are now creating messages, but there still is a difference. file uploads will include the file only and the file is physically uploaded to Slack. In contrast you can include multiple images in a message, along with text. And those images are not uploaded. You just provide a URL to it.
    – Erik Kalkoken
    Nov 12 at 15:17












  • Here is a screenshot showing both file upload and message with image attachment: i.imgur.com/w5dgw5s.png
    – Erik Kalkoken
    Nov 12 at 15:36










  • Okay... I know what you mean, but I am talking about uploading files and images on my physical harddrive, not something that is online anywhere. And I have to stick to my answer that I want to do both :) upload files and messages with files attached. I just tested my FileStream, by which I mean I converted it back to an image and wrote it to my harddrive. And it worked, so my fault has to lie somewhere in the "message" I send. Or the Object I actually create and then encode and send... but yet I'm clueless. And I am constantly on this issue - since 8 AM :(
    – Fabian Held
    Nov 12 at 15:59

















up vote
1
down vote

favorite












I need help with uploading files to Slack.



I have a Slack-App that is working with my code(below) so far. But all I can do is post messages. I can not attach images to the messages - because I do not understand how to use the so called "methods" and the syntax Slack is "showing" on their API-page.



This creates my "content" and below its just a Stream for reading a file I could upload:



    public class PostMessage
{


public FormUrlEncodedContent Content(string message, string file)
{
var values = new Dictionary<string, string>
{
{"token", "xoxp-myToken"},
{ "username", "X"},
{ "channel", "myChannel"},
{ "as_user", "false"},
{"text", message},
{ "content", file},
{ "attachments","[{ "fallback":"dummy", "text":"this is a waste of time"}]"}
};

var content = new FormUrlEncodedContent(values);

return content;
}
}

public class PostFile
{
String path = @"C:Usersf.heldDesktopHeld-Docsdagged.jpg";

public string ReadImageFile()
{
FileInfo fileInfo = new FileInfo(path);
long imageFileLength = fileInfo.Length;
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte imageData = br.ReadBytes((int)imageFileLength);
var str = Encoding.Default.GetString(imageData);
return str;
}
}
}


The client that communicates:



public class SlackClient
{
private readonly Uri _webhookUrl;
private readonly HttpClient _httpClient = new HttpClient {};

public SlackClient(Uri webhookUrl)
{
_webhookUrl = webhookUrl;
}

public async Task<HttpResponseMessage> SendMessageAsync(FormUrlEncodedContent content)
{
var response = await _httpClient.PostAsync(_webhookUrl, content);

return response;
}
}
}


The Main:



public static void Main(string args)
{
Task.WaitAll(IntegrateWithSlackAsync());
}

private static async Task IntegrateWithSlackAsync()
{
var webhookUrl = new Uri("https://slack.com/api/files.upload");
var slackClient = new SlackClient(webhookUrl);
PostMessage PM = new PostMessage();
PostFile PF = new PostFile();


while (true)
{
Console.Write("Type a message: ");
var message = Console.ReadLine();
var testFile = PF.ReadImageFile();
FormUrlEncodedContent payload = PM.Content(message, testFile);
var response = await slackClient.SendMessageAsync(payload);
var isValid = response.IsSuccessStatusCode ? "valid" : "invalid";
Console.WriteLine($"Received {isValid} response.");
Console.WriteLine(response);
response.Dispose();
}
}


}
}



If somebody has an example on what a upload has to look like. Or even better,



if somebody could really explain the syntax these Slack-Messages have to have.



That would be great! I still do not know where and HOW I should put the so called
"Accepted content types: multipart/form-data, application/x-www-form-urlencoded" to my upload. I just can not find examples on this...



Edit:



What confuses me needlesly is that Slack states they have an extra method called file.upload - but we shouldn't use it anymore, we should use just postMessage.



But how would I "pack" a file in a message? My syntax always seems to be off. Especially when it comes to "content"...
I just can not figure out what the c#-code has to look like. Where do I declare the aforementioned "content type"?



Another problem is, it always sends my messages through - means I get a 200-response from the server. But it never shows the file (which probably means the syntax is off) Or I get the 200-response but the message never shows in Slack.










share|improve this question
























  • Can you please clarify what your aim is: do you want to attach an image to your message OR do you want to upload a file to Slack?
    – Erik Kalkoken
    Nov 12 at 15:06










  • Hey Erik, well I need to be able to do both. But why is there even a difference? Everything is a file, right? I know you posted on my other question that with messages I could only post images. But Slack explicitely states that file uploads are treated as messages now (look here: api.slack.com/changelog/2018-05-file-threads-soon-tread ) . Or am I reading this wrong? When I use the SlackRTM it doesn't seem to behave differently when uploading images of any kind or files... so?! Thanks!
    – Fabian Held
    Nov 12 at 15:11












  • you are correct. files.upload are now creating messages, but there still is a difference. file uploads will include the file only and the file is physically uploaded to Slack. In contrast you can include multiple images in a message, along with text. And those images are not uploaded. You just provide a URL to it.
    – Erik Kalkoken
    Nov 12 at 15:17












  • Here is a screenshot showing both file upload and message with image attachment: i.imgur.com/w5dgw5s.png
    – Erik Kalkoken
    Nov 12 at 15:36










  • Okay... I know what you mean, but I am talking about uploading files and images on my physical harddrive, not something that is online anywhere. And I have to stick to my answer that I want to do both :) upload files and messages with files attached. I just tested my FileStream, by which I mean I converted it back to an image and wrote it to my harddrive. And it worked, so my fault has to lie somewhere in the "message" I send. Or the Object I actually create and then encode and send... but yet I'm clueless. And I am constantly on this issue - since 8 AM :(
    – Fabian Held
    Nov 12 at 15:59















up vote
1
down vote

favorite









up vote
1
down vote

favorite











I need help with uploading files to Slack.



I have a Slack-App that is working with my code(below) so far. But all I can do is post messages. I can not attach images to the messages - because I do not understand how to use the so called "methods" and the syntax Slack is "showing" on their API-page.



This creates my "content" and below its just a Stream for reading a file I could upload:



    public class PostMessage
{


public FormUrlEncodedContent Content(string message, string file)
{
var values = new Dictionary<string, string>
{
{"token", "xoxp-myToken"},
{ "username", "X"},
{ "channel", "myChannel"},
{ "as_user", "false"},
{"text", message},
{ "content", file},
{ "attachments","[{ "fallback":"dummy", "text":"this is a waste of time"}]"}
};

var content = new FormUrlEncodedContent(values);

return content;
}
}

public class PostFile
{
String path = @"C:Usersf.heldDesktopHeld-Docsdagged.jpg";

public string ReadImageFile()
{
FileInfo fileInfo = new FileInfo(path);
long imageFileLength = fileInfo.Length;
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte imageData = br.ReadBytes((int)imageFileLength);
var str = Encoding.Default.GetString(imageData);
return str;
}
}
}


The client that communicates:



public class SlackClient
{
private readonly Uri _webhookUrl;
private readonly HttpClient _httpClient = new HttpClient {};

public SlackClient(Uri webhookUrl)
{
_webhookUrl = webhookUrl;
}

public async Task<HttpResponseMessage> SendMessageAsync(FormUrlEncodedContent content)
{
var response = await _httpClient.PostAsync(_webhookUrl, content);

return response;
}
}
}


The Main:



public static void Main(string args)
{
Task.WaitAll(IntegrateWithSlackAsync());
}

private static async Task IntegrateWithSlackAsync()
{
var webhookUrl = new Uri("https://slack.com/api/files.upload");
var slackClient = new SlackClient(webhookUrl);
PostMessage PM = new PostMessage();
PostFile PF = new PostFile();


while (true)
{
Console.Write("Type a message: ");
var message = Console.ReadLine();
var testFile = PF.ReadImageFile();
FormUrlEncodedContent payload = PM.Content(message, testFile);
var response = await slackClient.SendMessageAsync(payload);
var isValid = response.IsSuccessStatusCode ? "valid" : "invalid";
Console.WriteLine($"Received {isValid} response.");
Console.WriteLine(response);
response.Dispose();
}
}


}
}



If somebody has an example on what a upload has to look like. Or even better,



if somebody could really explain the syntax these Slack-Messages have to have.



That would be great! I still do not know where and HOW I should put the so called
"Accepted content types: multipart/form-data, application/x-www-form-urlencoded" to my upload. I just can not find examples on this...



Edit:



What confuses me needlesly is that Slack states they have an extra method called file.upload - but we shouldn't use it anymore, we should use just postMessage.



But how would I "pack" a file in a message? My syntax always seems to be off. Especially when it comes to "content"...
I just can not figure out what the c#-code has to look like. Where do I declare the aforementioned "content type"?



Another problem is, it always sends my messages through - means I get a 200-response from the server. But it never shows the file (which probably means the syntax is off) Or I get the 200-response but the message never shows in Slack.










share|improve this question















I need help with uploading files to Slack.



I have a Slack-App that is working with my code(below) so far. But all I can do is post messages. I can not attach images to the messages - because I do not understand how to use the so called "methods" and the syntax Slack is "showing" on their API-page.



This creates my "content" and below its just a Stream for reading a file I could upload:



    public class PostMessage
{


public FormUrlEncodedContent Content(string message, string file)
{
var values = new Dictionary<string, string>
{
{"token", "xoxp-myToken"},
{ "username", "X"},
{ "channel", "myChannel"},
{ "as_user", "false"},
{"text", message},
{ "content", file},
{ "attachments","[{ "fallback":"dummy", "text":"this is a waste of time"}]"}
};

var content = new FormUrlEncodedContent(values);

return content;
}
}

public class PostFile
{
String path = @"C:Usersf.heldDesktopHeld-Docsdagged.jpg";

public string ReadImageFile()
{
FileInfo fileInfo = new FileInfo(path);
long imageFileLength = fileInfo.Length;
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte imageData = br.ReadBytes((int)imageFileLength);
var str = Encoding.Default.GetString(imageData);
return str;
}
}
}


The client that communicates:



public class SlackClient
{
private readonly Uri _webhookUrl;
private readonly HttpClient _httpClient = new HttpClient {};

public SlackClient(Uri webhookUrl)
{
_webhookUrl = webhookUrl;
}

public async Task<HttpResponseMessage> SendMessageAsync(FormUrlEncodedContent content)
{
var response = await _httpClient.PostAsync(_webhookUrl, content);

return response;
}
}
}


The Main:



public static void Main(string args)
{
Task.WaitAll(IntegrateWithSlackAsync());
}

private static async Task IntegrateWithSlackAsync()
{
var webhookUrl = new Uri("https://slack.com/api/files.upload");
var slackClient = new SlackClient(webhookUrl);
PostMessage PM = new PostMessage();
PostFile PF = new PostFile();


while (true)
{
Console.Write("Type a message: ");
var message = Console.ReadLine();
var testFile = PF.ReadImageFile();
FormUrlEncodedContent payload = PM.Content(message, testFile);
var response = await slackClient.SendMessageAsync(payload);
var isValid = response.IsSuccessStatusCode ? "valid" : "invalid";
Console.WriteLine($"Received {isValid} response.");
Console.WriteLine(response);
response.Dispose();
}
}


}
}



If somebody has an example on what a upload has to look like. Or even better,



if somebody could really explain the syntax these Slack-Messages have to have.



That would be great! I still do not know where and HOW I should put the so called
"Accepted content types: multipart/form-data, application/x-www-form-urlencoded" to my upload. I just can not find examples on this...



Edit:



What confuses me needlesly is that Slack states they have an extra method called file.upload - but we shouldn't use it anymore, we should use just postMessage.



But how would I "pack" a file in a message? My syntax always seems to be off. Especially when it comes to "content"...
I just can not figure out what the c#-code has to look like. Where do I declare the aforementioned "content type"?



Another problem is, it always sends my messages through - means I get a 200-response from the server. But it never shows the file (which probably means the syntax is off) Or I get the 200-response but the message never shows in Slack.







c# slack slack-api






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 at 16:46









Erik Kalkoken

12k32248




12k32248










asked Nov 12 at 14:20









Fabian Held

669




669












  • Can you please clarify what your aim is: do you want to attach an image to your message OR do you want to upload a file to Slack?
    – Erik Kalkoken
    Nov 12 at 15:06










  • Hey Erik, well I need to be able to do both. But why is there even a difference? Everything is a file, right? I know you posted on my other question that with messages I could only post images. But Slack explicitely states that file uploads are treated as messages now (look here: api.slack.com/changelog/2018-05-file-threads-soon-tread ) . Or am I reading this wrong? When I use the SlackRTM it doesn't seem to behave differently when uploading images of any kind or files... so?! Thanks!
    – Fabian Held
    Nov 12 at 15:11












  • you are correct. files.upload are now creating messages, but there still is a difference. file uploads will include the file only and the file is physically uploaded to Slack. In contrast you can include multiple images in a message, along with text. And those images are not uploaded. You just provide a URL to it.
    – Erik Kalkoken
    Nov 12 at 15:17












  • Here is a screenshot showing both file upload and message with image attachment: i.imgur.com/w5dgw5s.png
    – Erik Kalkoken
    Nov 12 at 15:36










  • Okay... I know what you mean, but I am talking about uploading files and images on my physical harddrive, not something that is online anywhere. And I have to stick to my answer that I want to do both :) upload files and messages with files attached. I just tested my FileStream, by which I mean I converted it back to an image and wrote it to my harddrive. And it worked, so my fault has to lie somewhere in the "message" I send. Or the Object I actually create and then encode and send... but yet I'm clueless. And I am constantly on this issue - since 8 AM :(
    – Fabian Held
    Nov 12 at 15:59




















  • Can you please clarify what your aim is: do you want to attach an image to your message OR do you want to upload a file to Slack?
    – Erik Kalkoken
    Nov 12 at 15:06










  • Hey Erik, well I need to be able to do both. But why is there even a difference? Everything is a file, right? I know you posted on my other question that with messages I could only post images. But Slack explicitely states that file uploads are treated as messages now (look here: api.slack.com/changelog/2018-05-file-threads-soon-tread ) . Or am I reading this wrong? When I use the SlackRTM it doesn't seem to behave differently when uploading images of any kind or files... so?! Thanks!
    – Fabian Held
    Nov 12 at 15:11












  • you are correct. files.upload are now creating messages, but there still is a difference. file uploads will include the file only and the file is physically uploaded to Slack. In contrast you can include multiple images in a message, along with text. And those images are not uploaded. You just provide a URL to it.
    – Erik Kalkoken
    Nov 12 at 15:17












  • Here is a screenshot showing both file upload and message with image attachment: i.imgur.com/w5dgw5s.png
    – Erik Kalkoken
    Nov 12 at 15:36










  • Okay... I know what you mean, but I am talking about uploading files and images on my physical harddrive, not something that is online anywhere. And I have to stick to my answer that I want to do both :) upload files and messages with files attached. I just tested my FileStream, by which I mean I converted it back to an image and wrote it to my harddrive. And it worked, so my fault has to lie somewhere in the "message" I send. Or the Object I actually create and then encode and send... but yet I'm clueless. And I am constantly on this issue - since 8 AM :(
    – Fabian Held
    Nov 12 at 15:59


















Can you please clarify what your aim is: do you want to attach an image to your message OR do you want to upload a file to Slack?
– Erik Kalkoken
Nov 12 at 15:06




Can you please clarify what your aim is: do you want to attach an image to your message OR do you want to upload a file to Slack?
– Erik Kalkoken
Nov 12 at 15:06












Hey Erik, well I need to be able to do both. But why is there even a difference? Everything is a file, right? I know you posted on my other question that with messages I could only post images. But Slack explicitely states that file uploads are treated as messages now (look here: api.slack.com/changelog/2018-05-file-threads-soon-tread ) . Or am I reading this wrong? When I use the SlackRTM it doesn't seem to behave differently when uploading images of any kind or files... so?! Thanks!
– Fabian Held
Nov 12 at 15:11






Hey Erik, well I need to be able to do both. But why is there even a difference? Everything is a file, right? I know you posted on my other question that with messages I could only post images. But Slack explicitely states that file uploads are treated as messages now (look here: api.slack.com/changelog/2018-05-file-threads-soon-tread ) . Or am I reading this wrong? When I use the SlackRTM it doesn't seem to behave differently when uploading images of any kind or files... so?! Thanks!
– Fabian Held
Nov 12 at 15:11














you are correct. files.upload are now creating messages, but there still is a difference. file uploads will include the file only and the file is physically uploaded to Slack. In contrast you can include multiple images in a message, along with text. And those images are not uploaded. You just provide a URL to it.
– Erik Kalkoken
Nov 12 at 15:17






you are correct. files.upload are now creating messages, but there still is a difference. file uploads will include the file only and the file is physically uploaded to Slack. In contrast you can include multiple images in a message, along with text. And those images are not uploaded. You just provide a URL to it.
– Erik Kalkoken
Nov 12 at 15:17














Here is a screenshot showing both file upload and message with image attachment: i.imgur.com/w5dgw5s.png
– Erik Kalkoken
Nov 12 at 15:36




Here is a screenshot showing both file upload and message with image attachment: i.imgur.com/w5dgw5s.png
– Erik Kalkoken
Nov 12 at 15:36












Okay... I know what you mean, but I am talking about uploading files and images on my physical harddrive, not something that is online anywhere. And I have to stick to my answer that I want to do both :) upload files and messages with files attached. I just tested my FileStream, by which I mean I converted it back to an image and wrote it to my harddrive. And it worked, so my fault has to lie somewhere in the "message" I send. Or the Object I actually create and then encode and send... but yet I'm clueless. And I am constantly on this issue - since 8 AM :(
– Fabian Held
Nov 12 at 15:59






Okay... I know what you mean, but I am talking about uploading files and images on my physical harddrive, not something that is online anywhere. And I have to stick to my answer that I want to do both :) upload files and messages with files attached. I just tested my FileStream, by which I mean I converted it back to an image and wrote it to my harddrive. And it worked, so my fault has to lie somewhere in the "message" I send. Or the Object I actually create and then encode and send... but yet I'm clueless. And I am constantly on this issue - since 8 AM :(
– Fabian Held
Nov 12 at 15:59














3 Answers
3






active

oldest

votes

















up vote
1
down vote



accepted










Here is a shorter working example showing how to just upload any file to Slack with C# only. The example will also automatically share the file the given channel.



I have included the logic to convert the API response from JSON, which will always be needed to determine if the API call was successful.



Note: This example requires Newtonsoft.Json



using System;
using System.Net;
using System.Collections.Specialized;
using System.Text;
using Newtonsoft.Json;

public class SlackExample
{
// classes for converting JSON respones from API method into objects
// note that only those properties are defind that are needed for this example

// reponse from file methods
class SlackFileResponse
{
public bool ok { get; set; }
public String error { get; set; }
public SlackFile file { get; set; }
}

// a slack file
class SlackFile
{
public String id { get; set; }
public String name { get; set; }
}

// main method with logic
public static void Main()
{
var parameters = new NameValueCollection();

// put your token here
parameters["token"] = "xoxp-YOUR-TOKEN";
parameters["channels"] = "test";

var client = new WebClient();
client.QueryString = parameters;
byte responseBytes = client.UploadFile(
"https://slack.com/api/files.upload",
"D:\temp\Stratios_down.jpg"
);

String responseString = Encoding.UTF8.GetString(responseBytes);

SlackFileResponse fileResponse =
JsonConvert.DeserializeObject<SlackFileResponse>(responseString);
}
}


About content types: Those are part of the header of a HTTP request and can be set manually in the WebClient object (see also this answer). However, for our case you can ignore it, because the default content types that WebClient is using for the POST request will work just fine.



Also see this answer on how to upload files with the WebClient class.






share|improve this answer



















  • 1




    You are a god among us mere mortals :) I'm kidding, but honestly your help is greatly appreciated! I hope this will not only help me but other people, too. Thank you so much for these clear examples, all your effort and work. Your answers are clear and precice, with good examples. From that I can learn. Again, thank you so much. And, of course, after testing your code I'll come back and upvote ;)
    – Fabian Held
    Nov 13 at 7:05












  • Now it won't upload via HttpClient. Says 'OK' in response I get. But image does not show in Slack. My uploadMethod: public async Task<HttpResponseMessage> UploadFile(byte file) { var requestContent = new MultipartFormDataContent(); var fileContent = new ByteArrayContent(file); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); requestContent.Add(fileContent, "dagged", "dagged.jpg"); var response = await _httpClient.PostAsync(_webhookUrl, requestContent); return response; }
    – Fabian Held
    Nov 13 at 11:06












  • Sorry for ugly formatting but no chars left....
    – Fabian Held
    Nov 13 at 11:10










  • Your WebClient-Method works fine. My HttPClient-Method works when sending a message with an attached image. But it won't work when I just want to upload any kind of file. I allways get {"ok":false,"error":"no_file_data"} Okay, I figured out that the problem seems to be that I use a byte as content. Other people seem to have the same problem. I dont understand why, because WebClient uses a byte-array as well... I'm hella confused :D Anyone has a good idea?
    – Fabian Held
    Nov 13 at 13:49












  • Your method has a couple of issues: 1) you are missing mandatory API parameters like token 2) You must not set multipart manually, its automatically set via MultipartFormDataContent() I will add another answer with a complete async example to clarify things.
    – Erik Kalkoken
    Nov 13 at 15:12


















up vote
1
down vote













Images in message



If you want to include an image in your message (along with some text) you can do so by adding images as message attachment to a normal message send with chat.postMessage.



For that you need a public URL of your image and that link with the image_url property to an attachment. That attachment can also contain text, and you can add multiple attachments to your message.



This is how it looks like:



enter image description here



And here is how this message looks in JSON:



{
"channel": "test",
"text": "This is a message example with images in the attachment",
"attachments": [
{
"fallback": "game over",
"text": "This is some text in the attachement",
"image_url": "https://i.imgur.com/jO9N3eJ.jpg"

}
]
}


Uploading images



The image URL needs to be publicly accessible on the Internet. So you need to host your image file on a public webserver or upload it to a image cloud service (e.g. imgur.com).



You can also use Slack as cloud service for your images. Here is how that works:




  1. Upload to Slack: Upload your image to your Slack workspace with files.upload


  2. Get public URL: Get a public URL for your image file with files.sharedPublicURL. Normally all files on Slack are private, but you can only use public URLs for message attachments.


  3. Send message: Include your image as attachment in a message: Use the permalink_public property of your image file as value for image_url



Example code



Here is a full working example in C# for first uploading an image to Slack and then using it in a message.



Note: This example requires Newtonsoft.Json.



using System;
using System.Net;
using System.Collections.Specialized;
using System.Text;
using Newtonsoft.Json;

public class SlackExample
{
// classes for converting JSON respones from API method into objects
// note that only those properties are defind that are needed for this example

// reponse from file methods
class SlackFileResponse
{
public bool ok { get; set; }
public String error { get; set; }
public SlackFile file { get; set; }
}

// a slack file
class SlackFile
{
public String id { get; set; }
public String name { get; set; }
public String permalink_public { get; set; }
}

// reponse from message methods
class SlackMessageResponse
{
public bool ok { get; set; }
public String error { get; set; }
public String channel { get; set; }
public String ts { get; set; }
}

// a slack message attachment
class SlackAttachment
{
public String fallback { get; set; }
public String text { get; set; }
public String image_url { get; set; }
}

// main method with logic
public static void Main()
{
String token = "xoxp-YOUR-TOKEN";


/////////////////////
// Step 1: Upload file to Slack

var parameters = new NameValueCollection();

// put your token here
parameters["token"] = token;

var client1 = new WebClient();
client1.QueryString = parameters;
byte responseBytes1 = client1.UploadFile(
"https://slack.com/api/files.upload",
"C:\Temp\Stratios_down.jpg"
);

String responseString1 = Encoding.UTF8.GetString(responseBytes1);

SlackFileResponse fileResponse1 =
JsonConvert.DeserializeObject<SlackFileResponse>(responseString1);

String fileId = fileResponse1.file.id;


/////////////////////
// Step 2: Make file public and get the URL

var parameters2 = new NameValueCollection();
parameters2["token"] = token;
parameters2["file"] = fileId;

var client2 = new WebClient();
byte responseBytes2 = client2.UploadValues("https://slack.com/api/files.sharedPublicURL", "POST", parameters2);

String responseString2 = Encoding.UTF8.GetString(responseBytes2);

SlackFileResponse fileResponse2 =
JsonConvert.DeserializeObject<SlackFileResponse>(responseString2);

String imageUrl = fileResponse2.file.permalink_public;


/////////////////////
// Step 3: Send message including freshly uploaded image as attachment

var parameters3 = new NameValueCollection();
parameters3["token"] = token;
parameters3["channel"] = "test_new";
parameters3["text"] = "test message 2";

// create attachment
SlackAttachment attachment = new SlackAttachment();
attachment.fallback = "this did not work";
attachment.text = "this is anattachment";
attachment.image_url = imageUrl;
SlackAttachment attachments = { attachment };
parameters3["attachments"] = JsonConvert.SerializeObject(attachments);

var client3 = new WebClient();
byte responseBytes3 = client3.UploadValues("https://slack.com/api/chat.postMessage", "POST", parameters3);

String responseString3 = Encoding.UTF8.GetString(responseBytes3);

SlackMessageResponse messageResponse =
JsonConvert.DeserializeObject<SlackMessageResponse>(responseString3);

}
}





share|improve this answer






























    up vote
    0
    down vote













    Here is another complete example for uploading a file to Slack, this time using the async approach with HttpClient.



    Note: This example requires Newtonsoft.Json.



    using Newtonsoft.Json;
    using System;
    using System.IO;
    using System.Net.Http;
    using System.Threading.Tasks;

    namespace SlackExample
    {
    class UploadFileExample
    {
    private static readonly HttpClient client = new HttpClient();

    // classes for converting JSON respones from API method into objects
    // note that only those properties are defind that are needed for this example

    // reponse from file methods
    class SlackFileResponse
    {
    public bool ok { get; set; }
    public String error { get; set; }
    public SlackFile file { get; set; }
    }

    // a slack file
    class SlackFile
    {
    public String id { get; set; }
    public String name { get; set; }
    }

    // sends a slack message asynchronous
    // throws exception if message can not be sent
    public static async Task UploadFileAsync(string token, string path, string channels)
    {
    // we need to send a request with multipart/form-data
    var multiForm = new MultipartFormDataContent();

    // add API method parameters
    multiForm.Add(new StringContent(token), "token");
    multiForm.Add(new StringContent(channels), "channels");

    // add file and directly upload it
    FileStream fs = File.OpenRead(path);
    multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(path));

    // send request to API
    var url = "https://slack.com/api/files.upload";
    var response = await client.PostAsync(url, multiForm);

    // fetch response from API
    var responseJson = await response.Content.ReadAsStringAsync();

    // convert JSON response to object
    SlackFileResponse fileResponse =
    JsonConvert.DeserializeObject<SlackFileResponse>(responseJson);

    // throw exception if sending failed
    if (fileResponse.ok == false)
    {
    throw new Exception(
    "failed to upload message: " + fileResponse.error
    );
    }
    else
    {
    Console.WriteLine(
    "Uploaded new file with id: " + fileResponse.file.id
    );
    }
    }

    static void Main(string args)
    {
    // upload this file and wait for completion
    UploadFileAsync(
    "xoxp-YOUR-TOKEN",
    "C:\temp\Stratios_down.jpg",
    "test"
    ).Wait();

    Console.ReadKey();

    }
    }

    }





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53264117%2fhow-to-upload-any-file-on-slack-via-slack-app-in-c-sharp%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      1
      down vote



      accepted










      Here is a shorter working example showing how to just upload any file to Slack with C# only. The example will also automatically share the file the given channel.



      I have included the logic to convert the API response from JSON, which will always be needed to determine if the API call was successful.



      Note: This example requires Newtonsoft.Json



      using System;
      using System.Net;
      using System.Collections.Specialized;
      using System.Text;
      using Newtonsoft.Json;

      public class SlackExample
      {
      // classes for converting JSON respones from API method into objects
      // note that only those properties are defind that are needed for this example

      // reponse from file methods
      class SlackFileResponse
      {
      public bool ok { get; set; }
      public String error { get; set; }
      public SlackFile file { get; set; }
      }

      // a slack file
      class SlackFile
      {
      public String id { get; set; }
      public String name { get; set; }
      }

      // main method with logic
      public static void Main()
      {
      var parameters = new NameValueCollection();

      // put your token here
      parameters["token"] = "xoxp-YOUR-TOKEN";
      parameters["channels"] = "test";

      var client = new WebClient();
      client.QueryString = parameters;
      byte responseBytes = client.UploadFile(
      "https://slack.com/api/files.upload",
      "D:\temp\Stratios_down.jpg"
      );

      String responseString = Encoding.UTF8.GetString(responseBytes);

      SlackFileResponse fileResponse =
      JsonConvert.DeserializeObject<SlackFileResponse>(responseString);
      }
      }


      About content types: Those are part of the header of a HTTP request and can be set manually in the WebClient object (see also this answer). However, for our case you can ignore it, because the default content types that WebClient is using for the POST request will work just fine.



      Also see this answer on how to upload files with the WebClient class.






      share|improve this answer



















      • 1




        You are a god among us mere mortals :) I'm kidding, but honestly your help is greatly appreciated! I hope this will not only help me but other people, too. Thank you so much for these clear examples, all your effort and work. Your answers are clear and precice, with good examples. From that I can learn. Again, thank you so much. And, of course, after testing your code I'll come back and upvote ;)
        – Fabian Held
        Nov 13 at 7:05












      • Now it won't upload via HttpClient. Says 'OK' in response I get. But image does not show in Slack. My uploadMethod: public async Task<HttpResponseMessage> UploadFile(byte file) { var requestContent = new MultipartFormDataContent(); var fileContent = new ByteArrayContent(file); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); requestContent.Add(fileContent, "dagged", "dagged.jpg"); var response = await _httpClient.PostAsync(_webhookUrl, requestContent); return response; }
        – Fabian Held
        Nov 13 at 11:06












      • Sorry for ugly formatting but no chars left....
        – Fabian Held
        Nov 13 at 11:10










      • Your WebClient-Method works fine. My HttPClient-Method works when sending a message with an attached image. But it won't work when I just want to upload any kind of file. I allways get {"ok":false,"error":"no_file_data"} Okay, I figured out that the problem seems to be that I use a byte as content. Other people seem to have the same problem. I dont understand why, because WebClient uses a byte-array as well... I'm hella confused :D Anyone has a good idea?
        – Fabian Held
        Nov 13 at 13:49












      • Your method has a couple of issues: 1) you are missing mandatory API parameters like token 2) You must not set multipart manually, its automatically set via MultipartFormDataContent() I will add another answer with a complete async example to clarify things.
        – Erik Kalkoken
        Nov 13 at 15:12















      up vote
      1
      down vote



      accepted










      Here is a shorter working example showing how to just upload any file to Slack with C# only. The example will also automatically share the file the given channel.



      I have included the logic to convert the API response from JSON, which will always be needed to determine if the API call was successful.



      Note: This example requires Newtonsoft.Json



      using System;
      using System.Net;
      using System.Collections.Specialized;
      using System.Text;
      using Newtonsoft.Json;

      public class SlackExample
      {
      // classes for converting JSON respones from API method into objects
      // note that only those properties are defind that are needed for this example

      // reponse from file methods
      class SlackFileResponse
      {
      public bool ok { get; set; }
      public String error { get; set; }
      public SlackFile file { get; set; }
      }

      // a slack file
      class SlackFile
      {
      public String id { get; set; }
      public String name { get; set; }
      }

      // main method with logic
      public static void Main()
      {
      var parameters = new NameValueCollection();

      // put your token here
      parameters["token"] = "xoxp-YOUR-TOKEN";
      parameters["channels"] = "test";

      var client = new WebClient();
      client.QueryString = parameters;
      byte responseBytes = client.UploadFile(
      "https://slack.com/api/files.upload",
      "D:\temp\Stratios_down.jpg"
      );

      String responseString = Encoding.UTF8.GetString(responseBytes);

      SlackFileResponse fileResponse =
      JsonConvert.DeserializeObject<SlackFileResponse>(responseString);
      }
      }


      About content types: Those are part of the header of a HTTP request and can be set manually in the WebClient object (see also this answer). However, for our case you can ignore it, because the default content types that WebClient is using for the POST request will work just fine.



      Also see this answer on how to upload files with the WebClient class.






      share|improve this answer



















      • 1




        You are a god among us mere mortals :) I'm kidding, but honestly your help is greatly appreciated! I hope this will not only help me but other people, too. Thank you so much for these clear examples, all your effort and work. Your answers are clear and precice, with good examples. From that I can learn. Again, thank you so much. And, of course, after testing your code I'll come back and upvote ;)
        – Fabian Held
        Nov 13 at 7:05












      • Now it won't upload via HttpClient. Says 'OK' in response I get. But image does not show in Slack. My uploadMethod: public async Task<HttpResponseMessage> UploadFile(byte file) { var requestContent = new MultipartFormDataContent(); var fileContent = new ByteArrayContent(file); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); requestContent.Add(fileContent, "dagged", "dagged.jpg"); var response = await _httpClient.PostAsync(_webhookUrl, requestContent); return response; }
        – Fabian Held
        Nov 13 at 11:06












      • Sorry for ugly formatting but no chars left....
        – Fabian Held
        Nov 13 at 11:10










      • Your WebClient-Method works fine. My HttPClient-Method works when sending a message with an attached image. But it won't work when I just want to upload any kind of file. I allways get {"ok":false,"error":"no_file_data"} Okay, I figured out that the problem seems to be that I use a byte as content. Other people seem to have the same problem. I dont understand why, because WebClient uses a byte-array as well... I'm hella confused :D Anyone has a good idea?
        – Fabian Held
        Nov 13 at 13:49












      • Your method has a couple of issues: 1) you are missing mandatory API parameters like token 2) You must not set multipart manually, its automatically set via MultipartFormDataContent() I will add another answer with a complete async example to clarify things.
        – Erik Kalkoken
        Nov 13 at 15:12













      up vote
      1
      down vote



      accepted







      up vote
      1
      down vote



      accepted






      Here is a shorter working example showing how to just upload any file to Slack with C# only. The example will also automatically share the file the given channel.



      I have included the logic to convert the API response from JSON, which will always be needed to determine if the API call was successful.



      Note: This example requires Newtonsoft.Json



      using System;
      using System.Net;
      using System.Collections.Specialized;
      using System.Text;
      using Newtonsoft.Json;

      public class SlackExample
      {
      // classes for converting JSON respones from API method into objects
      // note that only those properties are defind that are needed for this example

      // reponse from file methods
      class SlackFileResponse
      {
      public bool ok { get; set; }
      public String error { get; set; }
      public SlackFile file { get; set; }
      }

      // a slack file
      class SlackFile
      {
      public String id { get; set; }
      public String name { get; set; }
      }

      // main method with logic
      public static void Main()
      {
      var parameters = new NameValueCollection();

      // put your token here
      parameters["token"] = "xoxp-YOUR-TOKEN";
      parameters["channels"] = "test";

      var client = new WebClient();
      client.QueryString = parameters;
      byte responseBytes = client.UploadFile(
      "https://slack.com/api/files.upload",
      "D:\temp\Stratios_down.jpg"
      );

      String responseString = Encoding.UTF8.GetString(responseBytes);

      SlackFileResponse fileResponse =
      JsonConvert.DeserializeObject<SlackFileResponse>(responseString);
      }
      }


      About content types: Those are part of the header of a HTTP request and can be set manually in the WebClient object (see also this answer). However, for our case you can ignore it, because the default content types that WebClient is using for the POST request will work just fine.



      Also see this answer on how to upload files with the WebClient class.






      share|improve this answer














      Here is a shorter working example showing how to just upload any file to Slack with C# only. The example will also automatically share the file the given channel.



      I have included the logic to convert the API response from JSON, which will always be needed to determine if the API call was successful.



      Note: This example requires Newtonsoft.Json



      using System;
      using System.Net;
      using System.Collections.Specialized;
      using System.Text;
      using Newtonsoft.Json;

      public class SlackExample
      {
      // classes for converting JSON respones from API method into objects
      // note that only those properties are defind that are needed for this example

      // reponse from file methods
      class SlackFileResponse
      {
      public bool ok { get; set; }
      public String error { get; set; }
      public SlackFile file { get; set; }
      }

      // a slack file
      class SlackFile
      {
      public String id { get; set; }
      public String name { get; set; }
      }

      // main method with logic
      public static void Main()
      {
      var parameters = new NameValueCollection();

      // put your token here
      parameters["token"] = "xoxp-YOUR-TOKEN";
      parameters["channels"] = "test";

      var client = new WebClient();
      client.QueryString = parameters;
      byte responseBytes = client.UploadFile(
      "https://slack.com/api/files.upload",
      "D:\temp\Stratios_down.jpg"
      );

      String responseString = Encoding.UTF8.GetString(responseBytes);

      SlackFileResponse fileResponse =
      JsonConvert.DeserializeObject<SlackFileResponse>(responseString);
      }
      }


      About content types: Those are part of the header of a HTTP request and can be set manually in the WebClient object (see also this answer). However, for our case you can ignore it, because the default content types that WebClient is using for the POST request will work just fine.



      Also see this answer on how to upload files with the WebClient class.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 12 at 20:20

























      answered Nov 12 at 19:19









      Erik Kalkoken

      12k32248




      12k32248








      • 1




        You are a god among us mere mortals :) I'm kidding, but honestly your help is greatly appreciated! I hope this will not only help me but other people, too. Thank you so much for these clear examples, all your effort and work. Your answers are clear and precice, with good examples. From that I can learn. Again, thank you so much. And, of course, after testing your code I'll come back and upvote ;)
        – Fabian Held
        Nov 13 at 7:05












      • Now it won't upload via HttpClient. Says 'OK' in response I get. But image does not show in Slack. My uploadMethod: public async Task<HttpResponseMessage> UploadFile(byte file) { var requestContent = new MultipartFormDataContent(); var fileContent = new ByteArrayContent(file); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); requestContent.Add(fileContent, "dagged", "dagged.jpg"); var response = await _httpClient.PostAsync(_webhookUrl, requestContent); return response; }
        – Fabian Held
        Nov 13 at 11:06












      • Sorry for ugly formatting but no chars left....
        – Fabian Held
        Nov 13 at 11:10










      • Your WebClient-Method works fine. My HttPClient-Method works when sending a message with an attached image. But it won't work when I just want to upload any kind of file. I allways get {"ok":false,"error":"no_file_data"} Okay, I figured out that the problem seems to be that I use a byte as content. Other people seem to have the same problem. I dont understand why, because WebClient uses a byte-array as well... I'm hella confused :D Anyone has a good idea?
        – Fabian Held
        Nov 13 at 13:49












      • Your method has a couple of issues: 1) you are missing mandatory API parameters like token 2) You must not set multipart manually, its automatically set via MultipartFormDataContent() I will add another answer with a complete async example to clarify things.
        – Erik Kalkoken
        Nov 13 at 15:12














      • 1




        You are a god among us mere mortals :) I'm kidding, but honestly your help is greatly appreciated! I hope this will not only help me but other people, too. Thank you so much for these clear examples, all your effort and work. Your answers are clear and precice, with good examples. From that I can learn. Again, thank you so much. And, of course, after testing your code I'll come back and upvote ;)
        – Fabian Held
        Nov 13 at 7:05












      • Now it won't upload via HttpClient. Says 'OK' in response I get. But image does not show in Slack. My uploadMethod: public async Task<HttpResponseMessage> UploadFile(byte file) { var requestContent = new MultipartFormDataContent(); var fileContent = new ByteArrayContent(file); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); requestContent.Add(fileContent, "dagged", "dagged.jpg"); var response = await _httpClient.PostAsync(_webhookUrl, requestContent); return response; }
        – Fabian Held
        Nov 13 at 11:06












      • Sorry for ugly formatting but no chars left....
        – Fabian Held
        Nov 13 at 11:10










      • Your WebClient-Method works fine. My HttPClient-Method works when sending a message with an attached image. But it won't work when I just want to upload any kind of file. I allways get {"ok":false,"error":"no_file_data"} Okay, I figured out that the problem seems to be that I use a byte as content. Other people seem to have the same problem. I dont understand why, because WebClient uses a byte-array as well... I'm hella confused :D Anyone has a good idea?
        – Fabian Held
        Nov 13 at 13:49












      • Your method has a couple of issues: 1) you are missing mandatory API parameters like token 2) You must not set multipart manually, its automatically set via MultipartFormDataContent() I will add another answer with a complete async example to clarify things.
        – Erik Kalkoken
        Nov 13 at 15:12








      1




      1




      You are a god among us mere mortals :) I'm kidding, but honestly your help is greatly appreciated! I hope this will not only help me but other people, too. Thank you so much for these clear examples, all your effort and work. Your answers are clear and precice, with good examples. From that I can learn. Again, thank you so much. And, of course, after testing your code I'll come back and upvote ;)
      – Fabian Held
      Nov 13 at 7:05






      You are a god among us mere mortals :) I'm kidding, but honestly your help is greatly appreciated! I hope this will not only help me but other people, too. Thank you so much for these clear examples, all your effort and work. Your answers are clear and precice, with good examples. From that I can learn. Again, thank you so much. And, of course, after testing your code I'll come back and upvote ;)
      – Fabian Held
      Nov 13 at 7:05














      Now it won't upload via HttpClient. Says 'OK' in response I get. But image does not show in Slack. My uploadMethod: public async Task<HttpResponseMessage> UploadFile(byte file) { var requestContent = new MultipartFormDataContent(); var fileContent = new ByteArrayContent(file); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); requestContent.Add(fileContent, "dagged", "dagged.jpg"); var response = await _httpClient.PostAsync(_webhookUrl, requestContent); return response; }
      – Fabian Held
      Nov 13 at 11:06






      Now it won't upload via HttpClient. Says 'OK' in response I get. But image does not show in Slack. My uploadMethod: public async Task<HttpResponseMessage> UploadFile(byte file) { var requestContent = new MultipartFormDataContent(); var fileContent = new ByteArrayContent(file); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); requestContent.Add(fileContent, "dagged", "dagged.jpg"); var response = await _httpClient.PostAsync(_webhookUrl, requestContent); return response; }
      – Fabian Held
      Nov 13 at 11:06














      Sorry for ugly formatting but no chars left....
      – Fabian Held
      Nov 13 at 11:10




      Sorry for ugly formatting but no chars left....
      – Fabian Held
      Nov 13 at 11:10












      Your WebClient-Method works fine. My HttPClient-Method works when sending a message with an attached image. But it won't work when I just want to upload any kind of file. I allways get {"ok":false,"error":"no_file_data"} Okay, I figured out that the problem seems to be that I use a byte as content. Other people seem to have the same problem. I dont understand why, because WebClient uses a byte-array as well... I'm hella confused :D Anyone has a good idea?
      – Fabian Held
      Nov 13 at 13:49






      Your WebClient-Method works fine. My HttPClient-Method works when sending a message with an attached image. But it won't work when I just want to upload any kind of file. I allways get {"ok":false,"error":"no_file_data"} Okay, I figured out that the problem seems to be that I use a byte as content. Other people seem to have the same problem. I dont understand why, because WebClient uses a byte-array as well... I'm hella confused :D Anyone has a good idea?
      – Fabian Held
      Nov 13 at 13:49














      Your method has a couple of issues: 1) you are missing mandatory API parameters like token 2) You must not set multipart manually, its automatically set via MultipartFormDataContent() I will add another answer with a complete async example to clarify things.
      – Erik Kalkoken
      Nov 13 at 15:12




      Your method has a couple of issues: 1) you are missing mandatory API parameters like token 2) You must not set multipart manually, its automatically set via MultipartFormDataContent() I will add another answer with a complete async example to clarify things.
      – Erik Kalkoken
      Nov 13 at 15:12












      up vote
      1
      down vote













      Images in message



      If you want to include an image in your message (along with some text) you can do so by adding images as message attachment to a normal message send with chat.postMessage.



      For that you need a public URL of your image and that link with the image_url property to an attachment. That attachment can also contain text, and you can add multiple attachments to your message.



      This is how it looks like:



      enter image description here



      And here is how this message looks in JSON:



      {
      "channel": "test",
      "text": "This is a message example with images in the attachment",
      "attachments": [
      {
      "fallback": "game over",
      "text": "This is some text in the attachement",
      "image_url": "https://i.imgur.com/jO9N3eJ.jpg"

      }
      ]
      }


      Uploading images



      The image URL needs to be publicly accessible on the Internet. So you need to host your image file on a public webserver or upload it to a image cloud service (e.g. imgur.com).



      You can also use Slack as cloud service for your images. Here is how that works:




      1. Upload to Slack: Upload your image to your Slack workspace with files.upload


      2. Get public URL: Get a public URL for your image file with files.sharedPublicURL. Normally all files on Slack are private, but you can only use public URLs for message attachments.


      3. Send message: Include your image as attachment in a message: Use the permalink_public property of your image file as value for image_url



      Example code



      Here is a full working example in C# for first uploading an image to Slack and then using it in a message.



      Note: This example requires Newtonsoft.Json.



      using System;
      using System.Net;
      using System.Collections.Specialized;
      using System.Text;
      using Newtonsoft.Json;

      public class SlackExample
      {
      // classes for converting JSON respones from API method into objects
      // note that only those properties are defind that are needed for this example

      // reponse from file methods
      class SlackFileResponse
      {
      public bool ok { get; set; }
      public String error { get; set; }
      public SlackFile file { get; set; }
      }

      // a slack file
      class SlackFile
      {
      public String id { get; set; }
      public String name { get; set; }
      public String permalink_public { get; set; }
      }

      // reponse from message methods
      class SlackMessageResponse
      {
      public bool ok { get; set; }
      public String error { get; set; }
      public String channel { get; set; }
      public String ts { get; set; }
      }

      // a slack message attachment
      class SlackAttachment
      {
      public String fallback { get; set; }
      public String text { get; set; }
      public String image_url { get; set; }
      }

      // main method with logic
      public static void Main()
      {
      String token = "xoxp-YOUR-TOKEN";


      /////////////////////
      // Step 1: Upload file to Slack

      var parameters = new NameValueCollection();

      // put your token here
      parameters["token"] = token;

      var client1 = new WebClient();
      client1.QueryString = parameters;
      byte responseBytes1 = client1.UploadFile(
      "https://slack.com/api/files.upload",
      "C:\Temp\Stratios_down.jpg"
      );

      String responseString1 = Encoding.UTF8.GetString(responseBytes1);

      SlackFileResponse fileResponse1 =
      JsonConvert.DeserializeObject<SlackFileResponse>(responseString1);

      String fileId = fileResponse1.file.id;


      /////////////////////
      // Step 2: Make file public and get the URL

      var parameters2 = new NameValueCollection();
      parameters2["token"] = token;
      parameters2["file"] = fileId;

      var client2 = new WebClient();
      byte responseBytes2 = client2.UploadValues("https://slack.com/api/files.sharedPublicURL", "POST", parameters2);

      String responseString2 = Encoding.UTF8.GetString(responseBytes2);

      SlackFileResponse fileResponse2 =
      JsonConvert.DeserializeObject<SlackFileResponse>(responseString2);

      String imageUrl = fileResponse2.file.permalink_public;


      /////////////////////
      // Step 3: Send message including freshly uploaded image as attachment

      var parameters3 = new NameValueCollection();
      parameters3["token"] = token;
      parameters3["channel"] = "test_new";
      parameters3["text"] = "test message 2";

      // create attachment
      SlackAttachment attachment = new SlackAttachment();
      attachment.fallback = "this did not work";
      attachment.text = "this is anattachment";
      attachment.image_url = imageUrl;
      SlackAttachment attachments = { attachment };
      parameters3["attachments"] = JsonConvert.SerializeObject(attachments);

      var client3 = new WebClient();
      byte responseBytes3 = client3.UploadValues("https://slack.com/api/chat.postMessage", "POST", parameters3);

      String responseString3 = Encoding.UTF8.GetString(responseBytes3);

      SlackMessageResponse messageResponse =
      JsonConvert.DeserializeObject<SlackMessageResponse>(responseString3);

      }
      }





      share|improve this answer



























        up vote
        1
        down vote













        Images in message



        If you want to include an image in your message (along with some text) you can do so by adding images as message attachment to a normal message send with chat.postMessage.



        For that you need a public URL of your image and that link with the image_url property to an attachment. That attachment can also contain text, and you can add multiple attachments to your message.



        This is how it looks like:



        enter image description here



        And here is how this message looks in JSON:



        {
        "channel": "test",
        "text": "This is a message example with images in the attachment",
        "attachments": [
        {
        "fallback": "game over",
        "text": "This is some text in the attachement",
        "image_url": "https://i.imgur.com/jO9N3eJ.jpg"

        }
        ]
        }


        Uploading images



        The image URL needs to be publicly accessible on the Internet. So you need to host your image file on a public webserver or upload it to a image cloud service (e.g. imgur.com).



        You can also use Slack as cloud service for your images. Here is how that works:




        1. Upload to Slack: Upload your image to your Slack workspace with files.upload


        2. Get public URL: Get a public URL for your image file with files.sharedPublicURL. Normally all files on Slack are private, but you can only use public URLs for message attachments.


        3. Send message: Include your image as attachment in a message: Use the permalink_public property of your image file as value for image_url



        Example code



        Here is a full working example in C# for first uploading an image to Slack and then using it in a message.



        Note: This example requires Newtonsoft.Json.



        using System;
        using System.Net;
        using System.Collections.Specialized;
        using System.Text;
        using Newtonsoft.Json;

        public class SlackExample
        {
        // classes for converting JSON respones from API method into objects
        // note that only those properties are defind that are needed for this example

        // reponse from file methods
        class SlackFileResponse
        {
        public bool ok { get; set; }
        public String error { get; set; }
        public SlackFile file { get; set; }
        }

        // a slack file
        class SlackFile
        {
        public String id { get; set; }
        public String name { get; set; }
        public String permalink_public { get; set; }
        }

        // reponse from message methods
        class SlackMessageResponse
        {
        public bool ok { get; set; }
        public String error { get; set; }
        public String channel { get; set; }
        public String ts { get; set; }
        }

        // a slack message attachment
        class SlackAttachment
        {
        public String fallback { get; set; }
        public String text { get; set; }
        public String image_url { get; set; }
        }

        // main method with logic
        public static void Main()
        {
        String token = "xoxp-YOUR-TOKEN";


        /////////////////////
        // Step 1: Upload file to Slack

        var parameters = new NameValueCollection();

        // put your token here
        parameters["token"] = token;

        var client1 = new WebClient();
        client1.QueryString = parameters;
        byte responseBytes1 = client1.UploadFile(
        "https://slack.com/api/files.upload",
        "C:\Temp\Stratios_down.jpg"
        );

        String responseString1 = Encoding.UTF8.GetString(responseBytes1);

        SlackFileResponse fileResponse1 =
        JsonConvert.DeserializeObject<SlackFileResponse>(responseString1);

        String fileId = fileResponse1.file.id;


        /////////////////////
        // Step 2: Make file public and get the URL

        var parameters2 = new NameValueCollection();
        parameters2["token"] = token;
        parameters2["file"] = fileId;

        var client2 = new WebClient();
        byte responseBytes2 = client2.UploadValues("https://slack.com/api/files.sharedPublicURL", "POST", parameters2);

        String responseString2 = Encoding.UTF8.GetString(responseBytes2);

        SlackFileResponse fileResponse2 =
        JsonConvert.DeserializeObject<SlackFileResponse>(responseString2);

        String imageUrl = fileResponse2.file.permalink_public;


        /////////////////////
        // Step 3: Send message including freshly uploaded image as attachment

        var parameters3 = new NameValueCollection();
        parameters3["token"] = token;
        parameters3["channel"] = "test_new";
        parameters3["text"] = "test message 2";

        // create attachment
        SlackAttachment attachment = new SlackAttachment();
        attachment.fallback = "this did not work";
        attachment.text = "this is anattachment";
        attachment.image_url = imageUrl;
        SlackAttachment attachments = { attachment };
        parameters3["attachments"] = JsonConvert.SerializeObject(attachments);

        var client3 = new WebClient();
        byte responseBytes3 = client3.UploadValues("https://slack.com/api/chat.postMessage", "POST", parameters3);

        String responseString3 = Encoding.UTF8.GetString(responseBytes3);

        SlackMessageResponse messageResponse =
        JsonConvert.DeserializeObject<SlackMessageResponse>(responseString3);

        }
        }





        share|improve this answer

























          up vote
          1
          down vote










          up vote
          1
          down vote









          Images in message



          If you want to include an image in your message (along with some text) you can do so by adding images as message attachment to a normal message send with chat.postMessage.



          For that you need a public URL of your image and that link with the image_url property to an attachment. That attachment can also contain text, and you can add multiple attachments to your message.



          This is how it looks like:



          enter image description here



          And here is how this message looks in JSON:



          {
          "channel": "test",
          "text": "This is a message example with images in the attachment",
          "attachments": [
          {
          "fallback": "game over",
          "text": "This is some text in the attachement",
          "image_url": "https://i.imgur.com/jO9N3eJ.jpg"

          }
          ]
          }


          Uploading images



          The image URL needs to be publicly accessible on the Internet. So you need to host your image file on a public webserver or upload it to a image cloud service (e.g. imgur.com).



          You can also use Slack as cloud service for your images. Here is how that works:




          1. Upload to Slack: Upload your image to your Slack workspace with files.upload


          2. Get public URL: Get a public URL for your image file with files.sharedPublicURL. Normally all files on Slack are private, but you can only use public URLs for message attachments.


          3. Send message: Include your image as attachment in a message: Use the permalink_public property of your image file as value for image_url



          Example code



          Here is a full working example in C# for first uploading an image to Slack and then using it in a message.



          Note: This example requires Newtonsoft.Json.



          using System;
          using System.Net;
          using System.Collections.Specialized;
          using System.Text;
          using Newtonsoft.Json;

          public class SlackExample
          {
          // classes for converting JSON respones from API method into objects
          // note that only those properties are defind that are needed for this example

          // reponse from file methods
          class SlackFileResponse
          {
          public bool ok { get; set; }
          public String error { get; set; }
          public SlackFile file { get; set; }
          }

          // a slack file
          class SlackFile
          {
          public String id { get; set; }
          public String name { get; set; }
          public String permalink_public { get; set; }
          }

          // reponse from message methods
          class SlackMessageResponse
          {
          public bool ok { get; set; }
          public String error { get; set; }
          public String channel { get; set; }
          public String ts { get; set; }
          }

          // a slack message attachment
          class SlackAttachment
          {
          public String fallback { get; set; }
          public String text { get; set; }
          public String image_url { get; set; }
          }

          // main method with logic
          public static void Main()
          {
          String token = "xoxp-YOUR-TOKEN";


          /////////////////////
          // Step 1: Upload file to Slack

          var parameters = new NameValueCollection();

          // put your token here
          parameters["token"] = token;

          var client1 = new WebClient();
          client1.QueryString = parameters;
          byte responseBytes1 = client1.UploadFile(
          "https://slack.com/api/files.upload",
          "C:\Temp\Stratios_down.jpg"
          );

          String responseString1 = Encoding.UTF8.GetString(responseBytes1);

          SlackFileResponse fileResponse1 =
          JsonConvert.DeserializeObject<SlackFileResponse>(responseString1);

          String fileId = fileResponse1.file.id;


          /////////////////////
          // Step 2: Make file public and get the URL

          var parameters2 = new NameValueCollection();
          parameters2["token"] = token;
          parameters2["file"] = fileId;

          var client2 = new WebClient();
          byte responseBytes2 = client2.UploadValues("https://slack.com/api/files.sharedPublicURL", "POST", parameters2);

          String responseString2 = Encoding.UTF8.GetString(responseBytes2);

          SlackFileResponse fileResponse2 =
          JsonConvert.DeserializeObject<SlackFileResponse>(responseString2);

          String imageUrl = fileResponse2.file.permalink_public;


          /////////////////////
          // Step 3: Send message including freshly uploaded image as attachment

          var parameters3 = new NameValueCollection();
          parameters3["token"] = token;
          parameters3["channel"] = "test_new";
          parameters3["text"] = "test message 2";

          // create attachment
          SlackAttachment attachment = new SlackAttachment();
          attachment.fallback = "this did not work";
          attachment.text = "this is anattachment";
          attachment.image_url = imageUrl;
          SlackAttachment attachments = { attachment };
          parameters3["attachments"] = JsonConvert.SerializeObject(attachments);

          var client3 = new WebClient();
          byte responseBytes3 = client3.UploadValues("https://slack.com/api/chat.postMessage", "POST", parameters3);

          String responseString3 = Encoding.UTF8.GetString(responseBytes3);

          SlackMessageResponse messageResponse =
          JsonConvert.DeserializeObject<SlackMessageResponse>(responseString3);

          }
          }





          share|improve this answer














          Images in message



          If you want to include an image in your message (along with some text) you can do so by adding images as message attachment to a normal message send with chat.postMessage.



          For that you need a public URL of your image and that link with the image_url property to an attachment. That attachment can also contain text, and you can add multiple attachments to your message.



          This is how it looks like:



          enter image description here



          And here is how this message looks in JSON:



          {
          "channel": "test",
          "text": "This is a message example with images in the attachment",
          "attachments": [
          {
          "fallback": "game over",
          "text": "This is some text in the attachement",
          "image_url": "https://i.imgur.com/jO9N3eJ.jpg"

          }
          ]
          }


          Uploading images



          The image URL needs to be publicly accessible on the Internet. So you need to host your image file on a public webserver or upload it to a image cloud service (e.g. imgur.com).



          You can also use Slack as cloud service for your images. Here is how that works:




          1. Upload to Slack: Upload your image to your Slack workspace with files.upload


          2. Get public URL: Get a public URL for your image file with files.sharedPublicURL. Normally all files on Slack are private, but you can only use public URLs for message attachments.


          3. Send message: Include your image as attachment in a message: Use the permalink_public property of your image file as value for image_url



          Example code



          Here is a full working example in C# for first uploading an image to Slack and then using it in a message.



          Note: This example requires Newtonsoft.Json.



          using System;
          using System.Net;
          using System.Collections.Specialized;
          using System.Text;
          using Newtonsoft.Json;

          public class SlackExample
          {
          // classes for converting JSON respones from API method into objects
          // note that only those properties are defind that are needed for this example

          // reponse from file methods
          class SlackFileResponse
          {
          public bool ok { get; set; }
          public String error { get; set; }
          public SlackFile file { get; set; }
          }

          // a slack file
          class SlackFile
          {
          public String id { get; set; }
          public String name { get; set; }
          public String permalink_public { get; set; }
          }

          // reponse from message methods
          class SlackMessageResponse
          {
          public bool ok { get; set; }
          public String error { get; set; }
          public String channel { get; set; }
          public String ts { get; set; }
          }

          // a slack message attachment
          class SlackAttachment
          {
          public String fallback { get; set; }
          public String text { get; set; }
          public String image_url { get; set; }
          }

          // main method with logic
          public static void Main()
          {
          String token = "xoxp-YOUR-TOKEN";


          /////////////////////
          // Step 1: Upload file to Slack

          var parameters = new NameValueCollection();

          // put your token here
          parameters["token"] = token;

          var client1 = new WebClient();
          client1.QueryString = parameters;
          byte responseBytes1 = client1.UploadFile(
          "https://slack.com/api/files.upload",
          "C:\Temp\Stratios_down.jpg"
          );

          String responseString1 = Encoding.UTF8.GetString(responseBytes1);

          SlackFileResponse fileResponse1 =
          JsonConvert.DeserializeObject<SlackFileResponse>(responseString1);

          String fileId = fileResponse1.file.id;


          /////////////////////
          // Step 2: Make file public and get the URL

          var parameters2 = new NameValueCollection();
          parameters2["token"] = token;
          parameters2["file"] = fileId;

          var client2 = new WebClient();
          byte responseBytes2 = client2.UploadValues("https://slack.com/api/files.sharedPublicURL", "POST", parameters2);

          String responseString2 = Encoding.UTF8.GetString(responseBytes2);

          SlackFileResponse fileResponse2 =
          JsonConvert.DeserializeObject<SlackFileResponse>(responseString2);

          String imageUrl = fileResponse2.file.permalink_public;


          /////////////////////
          // Step 3: Send message including freshly uploaded image as attachment

          var parameters3 = new NameValueCollection();
          parameters3["token"] = token;
          parameters3["channel"] = "test_new";
          parameters3["text"] = "test message 2";

          // create attachment
          SlackAttachment attachment = new SlackAttachment();
          attachment.fallback = "this did not work";
          attachment.text = "this is anattachment";
          attachment.image_url = imageUrl;
          SlackAttachment attachments = { attachment };
          parameters3["attachments"] = JsonConvert.SerializeObject(attachments);

          var client3 = new WebClient();
          byte responseBytes3 = client3.UploadValues("https://slack.com/api/chat.postMessage", "POST", parameters3);

          String responseString3 = Encoding.UTF8.GetString(responseBytes3);

          SlackMessageResponse messageResponse =
          JsonConvert.DeserializeObject<SlackMessageResponse>(responseString3);

          }
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 12 at 19:10

























          answered Nov 12 at 15:59









          Erik Kalkoken

          12k32248




          12k32248






















              up vote
              0
              down vote













              Here is another complete example for uploading a file to Slack, this time using the async approach with HttpClient.



              Note: This example requires Newtonsoft.Json.



              using Newtonsoft.Json;
              using System;
              using System.IO;
              using System.Net.Http;
              using System.Threading.Tasks;

              namespace SlackExample
              {
              class UploadFileExample
              {
              private static readonly HttpClient client = new HttpClient();

              // classes for converting JSON respones from API method into objects
              // note that only those properties are defind that are needed for this example

              // reponse from file methods
              class SlackFileResponse
              {
              public bool ok { get; set; }
              public String error { get; set; }
              public SlackFile file { get; set; }
              }

              // a slack file
              class SlackFile
              {
              public String id { get; set; }
              public String name { get; set; }
              }

              // sends a slack message asynchronous
              // throws exception if message can not be sent
              public static async Task UploadFileAsync(string token, string path, string channels)
              {
              // we need to send a request with multipart/form-data
              var multiForm = new MultipartFormDataContent();

              // add API method parameters
              multiForm.Add(new StringContent(token), "token");
              multiForm.Add(new StringContent(channels), "channels");

              // add file and directly upload it
              FileStream fs = File.OpenRead(path);
              multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(path));

              // send request to API
              var url = "https://slack.com/api/files.upload";
              var response = await client.PostAsync(url, multiForm);

              // fetch response from API
              var responseJson = await response.Content.ReadAsStringAsync();

              // convert JSON response to object
              SlackFileResponse fileResponse =
              JsonConvert.DeserializeObject<SlackFileResponse>(responseJson);

              // throw exception if sending failed
              if (fileResponse.ok == false)
              {
              throw new Exception(
              "failed to upload message: " + fileResponse.error
              );
              }
              else
              {
              Console.WriteLine(
              "Uploaded new file with id: " + fileResponse.file.id
              );
              }
              }

              static void Main(string args)
              {
              // upload this file and wait for completion
              UploadFileAsync(
              "xoxp-YOUR-TOKEN",
              "C:\temp\Stratios_down.jpg",
              "test"
              ).Wait();

              Console.ReadKey();

              }
              }

              }





              share|improve this answer



























                up vote
                0
                down vote













                Here is another complete example for uploading a file to Slack, this time using the async approach with HttpClient.



                Note: This example requires Newtonsoft.Json.



                using Newtonsoft.Json;
                using System;
                using System.IO;
                using System.Net.Http;
                using System.Threading.Tasks;

                namespace SlackExample
                {
                class UploadFileExample
                {
                private static readonly HttpClient client = new HttpClient();

                // classes for converting JSON respones from API method into objects
                // note that only those properties are defind that are needed for this example

                // reponse from file methods
                class SlackFileResponse
                {
                public bool ok { get; set; }
                public String error { get; set; }
                public SlackFile file { get; set; }
                }

                // a slack file
                class SlackFile
                {
                public String id { get; set; }
                public String name { get; set; }
                }

                // sends a slack message asynchronous
                // throws exception if message can not be sent
                public static async Task UploadFileAsync(string token, string path, string channels)
                {
                // we need to send a request with multipart/form-data
                var multiForm = new MultipartFormDataContent();

                // add API method parameters
                multiForm.Add(new StringContent(token), "token");
                multiForm.Add(new StringContent(channels), "channels");

                // add file and directly upload it
                FileStream fs = File.OpenRead(path);
                multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(path));

                // send request to API
                var url = "https://slack.com/api/files.upload";
                var response = await client.PostAsync(url, multiForm);

                // fetch response from API
                var responseJson = await response.Content.ReadAsStringAsync();

                // convert JSON response to object
                SlackFileResponse fileResponse =
                JsonConvert.DeserializeObject<SlackFileResponse>(responseJson);

                // throw exception if sending failed
                if (fileResponse.ok == false)
                {
                throw new Exception(
                "failed to upload message: " + fileResponse.error
                );
                }
                else
                {
                Console.WriteLine(
                "Uploaded new file with id: " + fileResponse.file.id
                );
                }
                }

                static void Main(string args)
                {
                // upload this file and wait for completion
                UploadFileAsync(
                "xoxp-YOUR-TOKEN",
                "C:\temp\Stratios_down.jpg",
                "test"
                ).Wait();

                Console.ReadKey();

                }
                }

                }





                share|improve this answer

























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  Here is another complete example for uploading a file to Slack, this time using the async approach with HttpClient.



                  Note: This example requires Newtonsoft.Json.



                  using Newtonsoft.Json;
                  using System;
                  using System.IO;
                  using System.Net.Http;
                  using System.Threading.Tasks;

                  namespace SlackExample
                  {
                  class UploadFileExample
                  {
                  private static readonly HttpClient client = new HttpClient();

                  // classes for converting JSON respones from API method into objects
                  // note that only those properties are defind that are needed for this example

                  // reponse from file methods
                  class SlackFileResponse
                  {
                  public bool ok { get; set; }
                  public String error { get; set; }
                  public SlackFile file { get; set; }
                  }

                  // a slack file
                  class SlackFile
                  {
                  public String id { get; set; }
                  public String name { get; set; }
                  }

                  // sends a slack message asynchronous
                  // throws exception if message can not be sent
                  public static async Task UploadFileAsync(string token, string path, string channels)
                  {
                  // we need to send a request with multipart/form-data
                  var multiForm = new MultipartFormDataContent();

                  // add API method parameters
                  multiForm.Add(new StringContent(token), "token");
                  multiForm.Add(new StringContent(channels), "channels");

                  // add file and directly upload it
                  FileStream fs = File.OpenRead(path);
                  multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(path));

                  // send request to API
                  var url = "https://slack.com/api/files.upload";
                  var response = await client.PostAsync(url, multiForm);

                  // fetch response from API
                  var responseJson = await response.Content.ReadAsStringAsync();

                  // convert JSON response to object
                  SlackFileResponse fileResponse =
                  JsonConvert.DeserializeObject<SlackFileResponse>(responseJson);

                  // throw exception if sending failed
                  if (fileResponse.ok == false)
                  {
                  throw new Exception(
                  "failed to upload message: " + fileResponse.error
                  );
                  }
                  else
                  {
                  Console.WriteLine(
                  "Uploaded new file with id: " + fileResponse.file.id
                  );
                  }
                  }

                  static void Main(string args)
                  {
                  // upload this file and wait for completion
                  UploadFileAsync(
                  "xoxp-YOUR-TOKEN",
                  "C:\temp\Stratios_down.jpg",
                  "test"
                  ).Wait();

                  Console.ReadKey();

                  }
                  }

                  }





                  share|improve this answer














                  Here is another complete example for uploading a file to Slack, this time using the async approach with HttpClient.



                  Note: This example requires Newtonsoft.Json.



                  using Newtonsoft.Json;
                  using System;
                  using System.IO;
                  using System.Net.Http;
                  using System.Threading.Tasks;

                  namespace SlackExample
                  {
                  class UploadFileExample
                  {
                  private static readonly HttpClient client = new HttpClient();

                  // classes for converting JSON respones from API method into objects
                  // note that only those properties are defind that are needed for this example

                  // reponse from file methods
                  class SlackFileResponse
                  {
                  public bool ok { get; set; }
                  public String error { get; set; }
                  public SlackFile file { get; set; }
                  }

                  // a slack file
                  class SlackFile
                  {
                  public String id { get; set; }
                  public String name { get; set; }
                  }

                  // sends a slack message asynchronous
                  // throws exception if message can not be sent
                  public static async Task UploadFileAsync(string token, string path, string channels)
                  {
                  // we need to send a request with multipart/form-data
                  var multiForm = new MultipartFormDataContent();

                  // add API method parameters
                  multiForm.Add(new StringContent(token), "token");
                  multiForm.Add(new StringContent(channels), "channels");

                  // add file and directly upload it
                  FileStream fs = File.OpenRead(path);
                  multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(path));

                  // send request to API
                  var url = "https://slack.com/api/files.upload";
                  var response = await client.PostAsync(url, multiForm);

                  // fetch response from API
                  var responseJson = await response.Content.ReadAsStringAsync();

                  // convert JSON response to object
                  SlackFileResponse fileResponse =
                  JsonConvert.DeserializeObject<SlackFileResponse>(responseJson);

                  // throw exception if sending failed
                  if (fileResponse.ok == false)
                  {
                  throw new Exception(
                  "failed to upload message: " + fileResponse.error
                  );
                  }
                  else
                  {
                  Console.WriteLine(
                  "Uploaded new file with id: " + fileResponse.file.id
                  );
                  }
                  }

                  static void Main(string args)
                  {
                  // upload this file and wait for completion
                  UploadFileAsync(
                  "xoxp-YOUR-TOKEN",
                  "C:\temp\Stratios_down.jpg",
                  "test"
                  ).Wait();

                  Console.ReadKey();

                  }
                  }

                  }






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 13 at 15:51

























                  answered Nov 13 at 15:21









                  Erik Kalkoken

                  12k32248




                  12k32248






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53264117%2fhow-to-upload-any-file-on-slack-via-slack-app-in-c-sharp%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      鏡平學校

                      ꓛꓣだゔៀៅຸ໢ທຮ໕໒ ,ໂ'໥໓າ໼ឨឲ៵៭ៈゎゔit''䖳𥁄卿' ☨₤₨こゎもょの;ꜹꟚꞖꞵꟅꞛေၦေɯ,ɨɡ𛃵𛁹ޝ޳ޠ޾,ޤޒޯ޾𫝒𫠁သ𛅤チョ'サノބޘދ𛁐ᶿᶇᶀᶋᶠ㨑㽹⻮ꧬ꧹؍۩وَؠ㇕㇃㇪ ㇦㇋㇋ṜẰᵡᴠ 軌ᵕ搜۳ٰޗޮ޷ސޯ𫖾𫅀ल, ꙭ꙰ꚅꙁꚊꞻꝔ꟠Ꝭㄤﺟޱސꧨꧼ꧴ꧯꧽ꧲ꧯ'⽹⽭⾁⿞⼳⽋២៩ញណើꩯꩤ꩸ꩮᶻᶺᶧᶂ𫳲𫪭𬸄𫵰𬖩𬫣𬊉ၲ𛅬㕦䬺𫝌𫝼,,𫟖𫞽ហៅ஫㆔ాఆఅꙒꚞꙍ,Ꙟ꙱エ ,ポテ,フࢰࢯ𫟠𫞶 𫝤𫟠ﺕﹱﻜﻣ𪵕𪭸𪻆𪾩𫔷ġ,ŧآꞪ꟥,ꞔꝻ♚☹⛵𛀌ꬷꭞȄƁƪƬșƦǙǗdžƝǯǧⱦⱰꓕꓢႋ神 ဴ၀க௭எ௫ឫោ ' េㇷㇴㇼ神ㇸㇲㇽㇴㇼㇻㇸ'ㇸㇿㇸㇹㇰㆣꓚꓤ₡₧ ㄨㄟ㄂ㄖㄎ໗ツڒذ₶।ऩछएोञयूटक़कयँृी,冬'𛅢𛅥ㇱㇵㇶ𥄥𦒽𠣧𠊓𧢖𥞘𩔋цѰㄠſtʯʭɿʆʗʍʩɷɛ,əʏダヵㄐㄘR{gỚṖḺờṠṫảḙḭᴮᵏᴘᵀᵷᵕᴜᴏᵾq﮲ﲿﴽﭙ軌ﰬﶚﶧ﫲Ҝжюїкӈㇴffצּ﬘﭅﬈軌'ffistfflſtffतभफɳɰʊɲʎ𛁱𛁖𛁮𛀉 𛂯𛀞నఋŀŲ 𫟲𫠖𫞺ຆຆ ໹້໕໗ๆทԊꧢꧠ꧰ꓱ⿝⼑ŎḬẃẖỐẅ ,ờỰỈỗﮊDžȩꭏꭎꬻ꭮ꬿꭖꭥꭅ㇭神 ⾈ꓵꓑ⺄㄄ㄪㄙㄅㄇstA۵䞽ॶ𫞑𫝄㇉㇇゜軌𩜛𩳠Jﻺ‚Üမ႕ႌႊၐၸဓၞၞၡ៸wyvtᶎᶪᶹစဎ꣡꣰꣢꣤ٗ؋لㇳㇾㇻㇱ㆐㆔,,㆟Ⱶヤマފ޼ޝަݿݞݠݷݐ',ݘ,ݪݙݵ𬝉𬜁𫝨𫞘くせぉて¼óû×ó£…𛅑הㄙくԗԀ5606神45,神796'𪤻𫞧ꓐ㄁ㄘɥɺꓵꓲ3''7034׉ⱦⱠˆ“𫝋ȍ,ꩲ軌꩷ꩶꩧꩫఞ۔فڱێظペサ神ナᴦᵑ47 9238їﻂ䐊䔉㠸﬎ffiﬣ,לּᴷᴦᵛᵽ,ᴨᵤ ᵸᵥᴗᵈꚏꚉꚟ⻆rtǟƴ𬎎

                      Guess what letter conforming each word