Rename (Change) File name before adding to Zip using C# and VB.Net in ASP.Net

samsmuthu
 
on Sep 15, 2021 11:32 PM
Sample_601220.zip
586 Views

Hi

Referring you article, I have developed a code for download image files in to ZIP.

[Solved] Error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

So I have to modify above code for rename of image files then that files should into zip and download.

Please review above image 

  • Actual file path
  • New filename (Actual file name rename to New filename)

Please help me to modify above code for my requirement.

Thanking you,

samsmuthu

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Sep 20, 2021 01:43 AM

Hi samsmuthu,

Check this example. Now please take its reference and correct your code.

HTML

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:UpdatePanel ID="UpdatePanel3" runat="server">
        <ContentTemplate>
            <asp:Button ID="BtnShow" runat="server" Text="Show" />
            <asp:Button ID="btnDownload" runat="server" Text="Download" OnClick="DownloadFiles" />
        </ContentTemplate>
        <Triggers>
            <asp:PostBackTrigger ControlID="btnDownload" />
        </Triggers>
    </asp:UpdatePanel>
    <asp:UpdatePanel ID="UpdatePanel4" runat="server">
        <ContentTemplate>
            <asp:GridView ID="GridView2" runat="server"
                AutoGenerateColumns="false" AllowPaging="true"
                OnPageIndexChanging="GridView1_PageIndexChanging"
                PageSize="25" CssClass="GridViewStyle"
                EmptyDataText="No files available">
                <Columns>
                    <asp:TemplateField HeaderText="" ItemStyle-Wrap="false" ItemStyle-VerticalAlign="Middle" ItemStyle-HorizontalAlign="Left">
                        <ItemTemplate>
                            <asp:CheckBox ID="ChkSelect" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="File name" ItemStyle-Wrap="true" ItemStyle-VerticalAlign="Middle" ItemStyle-HorizontalAlign="Left">
                        <ItemTemplate>
                            <asp:Label ID="LblNewPhotoFileName" runat="server" Text='<%# Eval("NewPhotoFileName")%>' Visible="true"></asp:Label>
                            <asp:Label ID="LblPhotoFilePath" runat="server" Text='<%# Eval("PhotoFileName") %>' Visible="false"></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Photo" ItemStyle-Wrap="false" ItemStyle-VerticalAlign="Middle" ItemStyle-HorizontalAlign="Center">
                        <ItemTemplate>
                            <asp:Image ID="ImgPhoto" runat="server" BorderWidth="1px" Style="max-width: 150px; max-height: 100px;" Visible="true" ImageUrl='<%# Eval("PhotoFilePath")%>' />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

Namespaces

C#

using System.IO;
using Ionic.Zip;
using System.Collections.Generic;

VB.Net

Imports System.IO
Imports Ionic.Zip
Imports System.Collections.Generic

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string[] filePaths = Directory.GetFiles(Server.MapPath("~/Files/"));
        List<ListItem> files = new List<ListItem>();
        foreach (string filePath in filePaths)
        {
            files.Add(new ListItem(Path.GetFileName(filePath), filePath));
        }
        GridView1.DataSource = files;
        GridView1.DataBind();
    }
}
protected void DownloadFiles(object sender, EventArgs e)
{
    if (!Directory.Exists(Server.MapPath("~/New/")))
    {
        Directory.CreateDirectory(Server.MapPath("~/New/"));
    }
    using (ZipFile zip = new ZipFile())
    {
        zip.AlternateEncodingUsage = ZipOption.AsNecessary;
        zip.AddDirectoryByName("Files");
        int i = 1;
        foreach (GridViewRow row in GridView1.Rows)
        {
            if ((row.FindControl("chkSelect") as CheckBox).Checked)
            {
                string filePath = (row.FindControl("lblFilePath") as Label).Text;
                File.Copy(filePath, Server.MapPath("~/New/") + "Block_" + i + Path.GetExtension(filePath));
                zip.AddFile(Server.MapPath("~/New/") + "Block_" + i + Path.GetExtension(filePath), "Files");
            }
            i++;
        }
        Response.Clear();
        Response.BufferOutput = false;
        string zipName = string.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
        Response.ContentType = "application/zip";
        Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
        zip.Save(Response.OutputStream);
        Directory.Delete(Server.MapPath("~/New/"), true);
        Response.End();
    }
}

VB.Net

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Dim filePaths As String() = Directory.GetFiles(Server.MapPath("~/Files/"))
        Dim files As New List(Of ListItem)()
        For Each filePath As String In filePaths
            files.Add(New ListItem(Path.GetFileName(filePath), filePath))
        Next
        GridView1.DataSource = files
        GridView1.DataBind()
    End If
End Sub
Protected Sub DownloadFiles(ByVal sender As Object, ByVal e As EventArgs)
    If Not Directory.Exists(Server.MapPath("~/New/")) Then
        Directory.CreateDirectory(Server.MapPath("~/New/"))
    End If
    Using zip As ZipFile = New ZipFile()
        zip.AlternateEncodingUsage = ZipOption.AsNecessary
        zip.AddDirectoryByName("Files")
        Dim i As Integer = 1
        For Each row As GridViewRow In GridView1.Rows
            If (TryCast(row.FindControl("chkSelect"), CheckBox)).Checked Then
                Dim filePath As String = (TryCast(row.FindControl("lblFilePath"), Label)).Text
                File.Copy(filePath, Server.MapPath("~/New/") & "Block_" & i & Path.GetExtension(filePath))
                zip.AddFile(Server.MapPath("~/New/") & "Block_" & i & Path.GetExtension(filePath), "Files")
            End If
            i += 1
        Next
        Response.Clear()
        Response.BufferOutput = False
        Dim zipName As String = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"))
        Response.ContentType = "application/zip"
        Response.AddHeader("content-disposition", "attachment; filename=" & zipName)
        zip.Save(Response.OutputStream)
        Directory.Delete(Server.MapPath("~/New/"), True)
        Response.End()
    End Using
End Sub