2

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!";
}
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
NumanCS
  • 87
  • 1
  • 9

2 Answers2

2

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#

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
0

As I understand, you want to save to a .dat file the content of your StringBuilder. Then you want to compress the .dat file to a .zip file. Finally you want to send the .zip file to an FTP server.

Try something like this:

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;

    string zipFileName = "my_file.zip";
    string datFileName = "my_file.dat";
    string destinationFolder = @"c:\destinationFolder";
    string sourceFolder = @"c:\sourceFolder";
    string ftpDestinationPath = "ftp://1.2.3.4/my_file.zip";

    //Create .dat file with the StringBuilder content.
    File.WriteAllText(Path.Combine(sourceFolder, datFileName), sb.ToString());

    //Create .zip file containing the .dat file
    ZipFile.CreateFromDirectory(sourceFolder, Path.Combine(destinationFolder, zipFileName));

    //Send file to FTP server
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpDestinationPath);
    request.Method = WebRequestMethods.Ftp.UploadFile;

    request.Credentials = new NetworkCredential("userName", "password");

    byte[] fileContents;
    using (StreamReader sourceStream = new StreamReader(Path.Combine(destinationFolder, zipFileName)))
    {
        fileContents = File.ReadAllBytes(Path.Combine(destinationFolder, zipFileName));
    }

    request.ContentLength = fileContents.Length;

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

    using (FtpWebResponse ftpResponse = (FtpWebResponse)request.GetResponse()
    {
        return "Export Successfully!";
    }
}

Oscar Soler
  • 49
  • 1
  • 4
  • Hi, Thanks for your reply. I am adding the System.IO.Compression namespace but don't know how to edit my function for zip format. can you please edit my code for this task? thanks. – NumanCS Feb 25 '21 at 11:21
  • I've already posted a link with a [*complete code*](https://stackoverflow.com/q/46682983/850848#46683554) at your question. What do you need more? – Martin Prikryl Feb 25 '21 at 11:53
  • Hi, Thanks for your reply. I don't know how to edit my function for zip format. can you please edit my code here? thanks. @MartinPrikryl – NumanCS Feb 25 '21 at 12:22
  • Do you mean you want us to write the code for you? This is not a code writing service. Try yourself and ask questions about the problems you face. – Martin Prikryl Feb 25 '21 at 12:34
  • @Oscar You never write anything to the `sourceFolder` + Your code is inefficient compared to the one I've linked to. – Martin Prikryl Feb 25 '21 at 12:34
  • @Martin Prikryl Hi there, what do you mean with I never write anything to the ```sourceFolder```? Regards – Oscar Soler Feb 25 '21 at 12:41
  • The `ZipFile.CreateFromDirectory` creates a ZIP archive from the files in the directory specified by method's first argument. That's `sourceFolder`. But your code does not create any files in that folder (you do not use the `sourceFolder` anywhere else in your code). So the ZIP file will be empty. You write the `datFileName` file to `destinationFolder`, instead of `sourceFolder`. + Anyway, you do not need to create any temporary files. You can create the ZIP archive completely in-memory, as my answer shows. – Martin Prikryl Feb 25 '21 at 12:44
  • @MartinPrikryl can you please edit my code according to my data. regards – NumanCS Feb 25 '21 at 12:53
  • @MartinPrikryl https://stackoverflow.com/questions/66370122/how-to-import-zip-file-data-from-ftp-s-to-database-in-asp-net-mvc now please help me with this – NumanCS Feb 25 '21 at 14:12
  • @MartinPrikryl if I want to upload multiple .dat file as Zip format so what should do for this.? – NumanCS Feb 26 '21 at 10:45