Search code examples
c#.netasp.net-mvcftpzip

How to upload a string data as a ZIP archive to an FTP server in C#


Here is my code. I want to export/upload this .dat file into zip format to the FTP server. I try a lot but not find any solution. anyone can help me with this problem.

public string ExportVoid(FileSetups fileSetup, HttpPostedFileBase file)
{
    var sb = new System.Text.StringBuilder();

    var list = _context.VOIDS.ToList();
  
    foreach (var item in list)
    {
        sb.AppendFormat("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\r", item.Date, item.Time, item.Shift, item.EmployeeID, item.Amount, item.Items, item.DrawerOpen, item.Postpone, item.LocationID);
    }
    System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
   
    WebClient myWebClient = new WebClient();
    var dbftp = _context.FileSetup.SingleOrDefault();
    var a = dbftp.FTP;
    var v = Session["ClientId"];
    var d = DateTime.Now.ToString("MM_dd_yyyy_hh:mm:ss");
    string uriString = "ftp://MyFTP.com/Files/" + "Void" + ".dat";
    myWebClient.Credentials = new NetworkCredential("userName", "password");
    //Console.WriteLine("\nPlease enter the data to be posted to the URI {0}:", uriString);
    string postData = sb.ToString();
    // Apply ASCII Encoding to obtain the string as a byte array.
    byte[] postArray = Encoding.ASCII.GetBytes(postData);

    myWebClient.Headers.Add("Content-Disposition", "attachment; filename=" + "Void.dat");
    
    byte[] responseArray = myWebClient.UploadData(uriString, postArray);

    return "Export Successfully!";
}

Solution

  • If you want to zip an in-memory string (postData) and upload the zip to an FTP server, you can use:

    using (var memoryStream = new MemoryStream())
    {
        using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
        {
            // Repeat this block, if you want to add more files
            ZipArchiveEntry entry = archive.CreateEntry("void.dat");
    
            using (Stream entryStream = entry.Open())
            using (var writer = new StreamWriter(entryStream, Encoding.UTF8))
            {
                writer.Write(postData);
            }
        }
    
        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);
        }
    }
    

    If the text is small, so that a memory footprint does not matter, you can simplify the upload code (everything from memoryStream.Seek to the end) to:

        var client = new WebClient();
        client.Credentials = new NetworkCredential("username", "password");
        client.UploadData(
            "ftp://ftp.example.com/remote/path/archive.zip", memoryStream.ToArray());
    

    Based on Zip a directory and upload to FTP server without saving the .zip file locally in C#.


    Your related question about an opposite operation:
    How to import data from a ZIP file stored on FTP server to database in C#