Ad

C# Multiple Files Upload FTP

- 1 answer

I have a method where I save a single file. I want to complete the uploads in this way by making another method where I can save more than one file at the same time. How can I do that

         public static class FileUpload
{
    public static string UploadFtp(this IFormFile file, string Location, CdnSetting cdn)
    {
        var fileExtension = Path.GetExtension(file.FileName);

        var imageUrl = cdn.Url + Location + "/" + Guid.NewGuid().ToString() + fileExtension;

        using (WebClient client = new WebClient())
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(cdn.Address + imageUrl);
            request.Method = WebRequestMethods.Ftp.UploadFile;

            request.Credentials = new NetworkCredential(cdn.Name, cdn.Password);
            request.UsePassive = cdn.UsePassive;
            request.UseBinary = cdn.UseBinary;
            request.KeepAlive = cdn.KeepAlive;

            byte[] buffer = new byte[1024];
            var stream = file.OpenReadStream();
            byte[] fileContents;

            using (var ms = new MemoryStream())
            {
                int read;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                fileContents = ms.ToArray();
            }

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

            var response = (FtpWebResponse)request.GetResponse();
        }

        return cdn.Return + imageUrl;

       }
    }
Ad

Answer

You can reuse your method. Take a loop for the list of files.

public static IEnumerable<string> UploadFtp(this IFormFile[] files, string Location, CdnSetting cdn)
    {
        var result = new ConcurrentBag<string>();
        Parallel.ForEach(files, f =>
        {
            result.Add(UploadFtp(f, Location, cdn));
        });
        return result;
    }

If you want to upload the files one by one and not in parallel, a foreach loop is also possible.

Ad
source: stackoverflow.com
Ad