0

I have this azure function app that process errors. Before my app exits, I would like to write the errors in our memory as csv and then send the file to a client in an email.This is the code I have that stores file in the disk.

        using (var writer = new StreamWriter(fileName))
        using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
        {
            foreach (var row in content)
            {
                foreach (var col in row)
                {
                    csv.WriteField(col);
                }

                csv.NextRecord();
            }
        }
PPPP
  • 11
  • 4

1 Answers1

0

Just use MemoryStream instead of pointing to file and convert it to string later.

public string GetLogs()
{
    // use MemoryStream instead of file
    using (var ms = new MemoryStream())
    using (var writer = new StreamWriter(ms))
    {
        // write everything
        ...

        // ensure write is finished
        writer.Flush();

        // convert memory stream to string
        return Encoding.UTF8.GetString(ms.ToArray());
    }
}

P.S. But pay attention to what MohitGanorkar-MT wrote.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Aleksej Vasinov
  • 2,662
  • 28
  • 29
  • .NET strings are UTF16 so this will fail from the start. You can use a StringWriter instead of a MemoryStream and get an actual string directly but, to create an attachment, you'll have to convert the string to a byte array again – Panagiotis Kanavos Jul 05 '22 at 07:26
  • As for using App insights, that's almost certainly a bad idea *unless* the OP want's exactly the scenario App insights is for - distributed logging. That's not the case here. The OP wants to `send the file to a client in an email.`. This isn't a logging question – Panagiotis Kanavos Jul 05 '22 at 07:40
  • It works, copy and test it :) I think, that the question is from beginner, so I will not going to advise him good architecture solution. – Aleksej Vasinov Jul 05 '22 at 07:58
  • 1
    You're right, but only because StreamWriter uses UTF8 by default. If you want a string though, you don't need a stream in the first place, that simply generates temporary buffers for the GC to collect. To send an email attachment though, you need a byte buffer, not a string – Panagiotis Kanavos Jul 05 '22 at 08:08
  • Besides, the OP is already using CsvWriter which means they are sending actual data files, not just unstructured log messages – Panagiotis Kanavos Jul 05 '22 at 08:09