Passing Datatable Data As Attachement In Mail

public string sendNetcoreEmail(string htmlString, string sub, string from, string to, string[] bccid, DataTable dt) {
    string ret = "true";
    try {
        MailMessage message = new MailMessage();
        SmtpClient smtp = new SmtpClient();
        message.From = new MailAddress(from, "sendername");
        if (bccid != null) {
            foreach(string bccMailID in bccid) {
                message.Bcc.Add(new MailAddress(bccMailID));
            }
        }
        message.To.Add(new MailAddress(to));
        message.Subject = sub;
        message.IsBodyHtml = true;
        message.Body = htmlString;
        var stream = new MemoryStream();
        var writer = new StreamWriter(stream);
        for (int i = 0; i < dt.Columns.Count; i++) {
            writer.Write(dt.Columns[i]);
            if (i < dt.Columns.Count - 1) {
                writer.Write(",");
            }
        }
        writer.Write(writer.NewLine);
        foreach(DataRow dr in dt.Rows) {
            for (int i = 0; i < dt.Columns.Count; i++) {
                if (!Convert.IsDBNull(dr[i])) {
                    string value = dr[i].ToString();
                    if (value.Contains(',')) {
                        value = String.Format("\"{0}\"", value);
                        writer.Write(value);
                    } else {
                        writer.Write(dr[i].ToString());
                    }
                }
                if (i < dt.Columns.Count - 1) {
                    writer.Write(",");
                }
            }
            writer.Write(writer.NewLine);
        } // using UTF-8 encoding by default //writer.WriteLine("Comma,Seperated,Values,...");
        writer.Flush();
        stream.Position = 0; // read from the start of what was written
        message.Attachments.Add(new Attachment(stream, "MyReferral.csv", "text/csv")); /**/
        smtp.Port = 587;
        smtp.Host = "smtpbp.falconide.com"; //for netcore host
        smtp.EnableSsl = false;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new NetworkCredential("miraeassetcmdev", "59pXz*Nt5$AZSYL3");
        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtp.Send(message);
    } catch (Exception ex) {
        ret = ex.Message.ToString();
    }
    return ret;
}