none
Extract and Read a zip File in .net 4.5+ RRS feed

  • Question

  • I am trying to read a zip file and extract it and read the contents of the file and insert row by row into sql db.

    The zip file contents are having huge size text files and wanted to read it one by one with ADO.NET.

    below is the code am trying.

    but am not able to get it right.

    am using the below LOC :

    var tempFileName = Path.GetTempFileName()

    here,a  temp file , .tmp extension is created and i am unable to fine the final path after processing :

    C:\Users\muysername1\AppData\Local\Temp\tmp8B51.tmp

    and finally when the code is executed, am getting erorr: the path could not be found! 

    what am I doing wrong? which API should i use to extract and read ?

    can anyone help,  with the correct source code :

     try
                {
                    pathforsaving = Server.MapPath(@"~/App_Data/");

                    if (postedFiles != null)
                    {
                        string sfileName = Path.GetFileName(postedFiles.FileName);
                        string uploadFilePathandname = Path.Combine(pathforsaving, sfileName);

                        postedFiles.SaveAs(uploadFilePathandname);

                        //ZipFile.ExtractToDirectory(uploadFilePathandname, pathforsaving);

                        //read files within the zip file without extracting 
                        using (var zipStream = new FileStream(uploadFilePathandname, FileMode.Open))
                        using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Read))
                        {
                            foreach (var entry in archive.Entries)
                            {
                                if (entry != null && !string.IsNullOrEmpty(entry.ToString()))
                                {
                                    using (var stream = entry.Open())
                                    {
                                        using (var streamReader = new StreamReader(uploadFilePathandname))
                                        {
                  }





    • Edited by SaMolPP Friday, May 24, 2019 7:50 AM
    Thursday, May 23, 2019 8:14 AM

Answers

  • Hi SaMolPP,

    Thank you for posting here.

    Based on your description, you want to read a zip file and extract it and read the contents of the file and insert row by row into sql db.

    I make a simple code, you could have a look.

    static void Main(string[] args)
            {
                string zipPath = @"D:\test.zip";
                string extractPath = @"D:\";
                string newpath = null;
    
                using (ZipArchive archive = ZipFile.OpenRead(zipPath))
                {
                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        if (entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
                        {
                            entry.ExtractToFile(Path.Combine(extractPath, entry.FullName));
                            newpath = Path.Combine(extractPath, entry.FullName);
                        }
                    }
                }
    
                string[] array = File.ReadAllLines(@newpath);
                string conn = @"Data Source=(localdb)\ProjectsV13;Initial Catalog=mlhelper;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
                using (SqlConnection connection = new SqlConnection(conn))
                {
                    connection.Open();
                    for (int i = 0; i < array.Length; i++)
                    {
                        string sql = string.Format("insert into TextTodb(Id,Text)values('{0}','{1}')", i, array[i]);
                        using (SqlCommand cmd = new SqlCommand(sql, connection))
                        {
                            cmd.ExecuteNonQuery();
                        }
                    }
                    
                }
    
            }

    Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, May 24, 2019 5:12 AM
    Moderator

All replies

  • What do you mean by extract the contents and store the contents of the file into a database? A zip file may contain zero or more files contained in zero or more folders. Each file can be just about anything. Please clarify exactly what you're trying to do.

    To extract a zip file you can use ZipArchive or ZipFile. Both will give you access to the file(s) in the zip. After that you can use the standard File API to read the files or do whatever you want. But of course you cannot directly upload a file into a database. That wouldn't make sense.


    Michael Taylor http://www.michaeltaylorp3.net

    Thursday, May 23, 2019 2:43 PM
    Moderator
  • Hi SaMolPP,

    Thank you for posting here.

    Based on your description, you want to read a zip file and extract it and read the contents of the file and insert row by row into sql db.

    I make a simple code, you could have a look.

    static void Main(string[] args)
            {
                string zipPath = @"D:\test.zip";
                string extractPath = @"D:\";
                string newpath = null;
    
                using (ZipArchive archive = ZipFile.OpenRead(zipPath))
                {
                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        if (entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
                        {
                            entry.ExtractToFile(Path.Combine(extractPath, entry.FullName));
                            newpath = Path.Combine(extractPath, entry.FullName);
                        }
                    }
                }
    
                string[] array = File.ReadAllLines(@newpath);
                string conn = @"Data Source=(localdb)\ProjectsV13;Initial Catalog=mlhelper;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
                using (SqlConnection connection = new SqlConnection(conn))
                {
                    connection.Open();
                    for (int i = 0; i < array.Length; i++)
                    {
                        string sql = string.Format("insert into TextTodb(Id,Text)values('{0}','{1}')", i, array[i]);
                        using (SqlCommand cmd = new SqlCommand(sql, connection))
                        {
                            cmd.ExecuteNonQuery();
                        }
                    }
                    
                }
    
            }

    Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, May 24, 2019 5:12 AM
    Moderator