0

How do I send a file using Discord Webhook in C#?

I already tried looking at other threads like this, but they didn't have any answers that could help me.

This is the webhook class:

public class DcWebHook : IDisposable
    {
        private readonly WebClient dcweblient;
        private static NameValueCollection values = new NameValueCollection();
        public string WebHook { get; set; }
        public string UserName { get; set; }
        public string ProfilePicture { get; set; }

        public DcWebHook()
        {
            dcweb = new WebClient();
        }


        public void SendMessage(string msgSend)
        {
            values.Add("username", UserName);
            values.Add("avatar_url", ProfilePicture);
            values.Add("content", msgSend);
        }

        public void SendFile(string file)
        {
            values.Add("file", file);
        }

        public void uploadthevalues()
        {
            dcweb.UploadValues(WebHook, values);
        }

        public void Dispose()
        {
            dcweb.Dispose();
        }
    }

This is the sending part:

dcWeb.ProfilePicture = "link";
dcWeb.UserName = "test";
dcWeb.WebHook = "webhooklink";
dcWeb.SendMessage("attachment test");
dcWeb.uploadthevalues();
dcWeb.SendFile("local file address(C:\test.txt)");

The first message sends sucessfully, but the file does not attach, if anyone has any solutions for this, it would be greatly appreciated.

Thank you in advance.

Note: I'm using this as a reference: https://discord.com/developers/docs/resources/webhook

edit: I have found out that I can use .UploadFile to upload the file, but I can't seem to make it upload in the same message.

hcker49
  • 11
  • 2
  • [this answer](https://stackoverflow.com/a/19983672/28004) will help you as you can see from the docs, you need to send as `multipart/form-data` and you're not doing so, plus, it is a `POST` and from your code, you're not even changing that. I would suggest that you use a library to perform REST calls, like [RestSharp](http://restsharp.org/), or is you're using Discord API, why not a [C# Wrapper](https://github.com/discord-net/Discord.Net)? – balexandre May 11 '20 at 14:59

1 Answers1

0

You could use dcweb.UploadFile, you will have to use OpenFileDialog though, or you could reference it completely from your machine (eg. C:/user/Documents/File), which is a bit harder.

Example:

public void Test()
    {
        OpenFileDialog openfile = new OpenFileDialog();

        if (openfile.ShowDialog() == DialogResult.OK)
        {
            dcweb.UploadFile(WebHook, openfile.FileName);
        }
    }

This should upload your file to discord, it supports all types (including pdfs!)