0

What I'm trying to do, is create an Azure Function that generates certain files. I then have to:

  1. upload these files to an FTP server or Webdav server
  2. archive them to a storage account.

What solution do you recommend? How can I store these temp files while I perform the operations above? (Sorry for this n00bish question, this is my first Azure Function that I'm working on.)

  • 1
    stored them as blobs in a storage container? https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blobs-introduction – codebrane Oct 28 '21 at 12:21

1 Answers1

0

Thank you Martin-Prikryl. Posting your suggestion as an answer to help the other community members.

upload these files to an FTP server or Webdav server

Below is the example code on how to upload .docx to FTP server using memorystream. Just copy your stream to the FTP request stream:

Stream requestStream = ftpRequest.GetRequestStream();
stream.CopyTo(requestStream);
requestStream.Close();

For a string (assuming the contents is a text):

byte[] bytes = Encoding.UTF8.GetBytes(data);

using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(bytes, 0, bytes.Length);
}

Or even better use the StreamWriter

using (Stream requestStream = request.GetRequestStream())
using (StreamWriter writer = new StreamWriter(requestStream, Encoding.UTF8))
{
    writer.Write(data);
}

If the contents is a text, you should use the text mode:

request.UseBinary = false;

Check the SO for More Information.

archive them to a storage account.

Below is the example on how to archive files

using (Stream memoryStream = new MemoryStream())
{
    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
    {
        foreach (string path in Directory.EnumerateFiles(@"C:\source\directory"))
        {
            ZipArchiveEntry entry = archive.CreateEntry(Path.GetFileName(path));

            using (Stream entryStream = entry.Open())
            using (Stream fileStream = File.OpenRead(path))
            {
                fileStream.CopyTo(entryStream);
            }
        }
    }

    memoryStream.Seek(0, SeekOrigin.Begin);

    var request =
        WebRequest.Create("ftp://ftp.example.com/remote/path/archive.zip");
    request.Credentials = new NetworkCredential("username", "password");
    request.Method = WebRequestMethods.Ftp.UploadFile;
    using (Stream ftpStream = request.GetRequestStream())
    {
        memoryStream.CopyTo(ftpStream);
    }
}

Check the SO for complete information.

SaiSakethGuduru
  • 2,218
  • 1
  • 5
  • 15