简体   繁体   中英

How to extract data from stored procedure and dynamically create a zip folder and add csv file

The below is what I want to achieve and my below coding is what I have done so far.

I am not sure if what I am doing is the best approach to achieving this task.

The issue starts with creating a zip folder dynamically and adding a file so that I can send it via email.

  1. Query the stored procedure and get the data
  2. Convert returned data from stored procedure to CSV file.
  3. Dynamically create a zip folder and store the CSV file.
  4. Zip file and CSV name should be the same. (name will come from date range eg 'yyy-dd-mm')
  5. Attach the zip folder to and email and send it to the client.
  6. Finally save the zip folder to the local directory or save.

Please advise if there's a better way of doing it to achieve my task.

Dummy data:

DataTable dummyData = new DataTable();
//columns
dummyData.Columns.Add("Id", typeof(int));
dummyData.Columns.Add("Make", typeof(string));
dummyData.Columns.Add("Model", typeof(string));

//data
dummyData.Rows.Add(111, "Toyota", "Hilux");
dummyData.Rows.Add(102, "Isuzu", "KB");
dummyData.Rows.Add(212, "Mazda", "323");

Writing to CSV file,saving to path,and sending an email:

if (dummyData != null && dummyData.Rows.Count > 0)
{
    var fileName = "Testing11.csv";

    StringBuilder sb = new StringBuilder();

    string[] columnNames = dummyData.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToArray();
    sb.AppendLine(string.Join(",", columnNames));

    foreach (DataRow row in dummyData.Rows)
    {
        IEnumerable<string> fields = row.ItemArray.Select(field => string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
        sb.AppendLine(string.Join(",", fields));
    }

    string newFile = @"C:\Testing\" + fileName + "";

    // for testing purpose
    if (File.Exists(newFile))
    {
        File.Delete(newFile);
    }

    // Write and save the file to directory.
    File.WriteAllText(newFile, sb.ToString());

    // Add file to Zip folder
    // Not to sure how i can zip it

    // Attach zip folder and send email.
    StringBuilder emailText = new StringBuilder();
    emailText.AppendLine("Good day,");
    emailText.AppendLine("<br/>");
    emailText.AppendLine("<br/>");
    emailText.AppendLine("Please find attached copy of the file.");
    emailText.AppendLine("<br/>");
    emailText.AppendLine("<br/>");
    emailText.AppendLine("Please don't hesitate to contact us if there is any discrepancies on the file.");
    emailText.AppendLine("<br/>");
    emailText.AppendLine("<br/>");
    emailText.AppendLine("Regards,");
    emailText.AppendLine("<br/>");
    emailText.AppendLine(company);
    emailText.AppendLine("<br/>");
    emailText.AppendLine("<br/>");
    emailText.AppendLine("This email was sent from an unattended email address!");

    // Send an email to client
    string emailSubject = newFile;
    SendEmail(emailTo, emailSubject, emailText.ToString(),newFile);
}
else
{
    throw new Exception("Not found!");
}

Sending the email:

public void SendEmail(string to, string subject, string body, string attachmentFileName = null)
{
        try
        {
            SmtpClient client = new SmtpClient("mySTP",25)
            {
                DeliveryMethod = SmtpDeliveryMethod.Network
            };

            MailMessage mailMessage = new MailMessage();
            mailMessage.From = new MailAddress("emailfrom@example.com");

            foreach (string address in to.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                mailMessage.To.Add(address);

            mailMessage.IsBodyHtml = true;
            mailMessage.Body = body;
            mailMessage.Subject = subject;

            if (attachmentFileName != null)
            {
                mailMessage.Attachments.Add(new Attachment(attachmentFileName));
            }
            else 
            {
                throw new Exception("Oops! No attachment file found");
            }

            client.Send(mailMessage);
        }
        catch (Exception ex)
        {
            throw ex;
        }
}

I have first created a temp folder which I then dump a file into it. After that, I then zip the folder and attach it and send it to an email.

Step 1.

 string fileName = testingfile.csv;
 string newFile = @"C:\Testing\" + fileName + "";

I then create a zip folder. I have given the zip folder the same name as the file name as per the request.

Step 2.

 var zipFolder = fileName + ".zip";
 ZipFile.CreateFromDirectory(@"C:\Testing\", zipFolder);

Now I am sending an email to the client with the attached zip folder which contains the file.

Step 3.

string emailSubject = zipFolder;
SendEmail(emailTo, emailSubject, emailText.ToString(),zipFolder);

Hope it will help someone one day!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM