Saturday 17 January 2015

How to save & retrive PDF file into server c#

Hi friends,
Here I am going to explain you How to save PDF files in SQL Database[not actually] and how to retrive or download the same from server...


Design Part of our WebForm
<div>
<h2 style="color: #0066FF; font-weight: bold;">
<u>Select your file to upload</u>
</h2>
       <div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</div>

<div>
<asp:FileUpload ID="FileUploadToServer" Width="300px" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload File" OnClick="btnUpload_Click" ValidationGroup="vg" />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
            Text="Create Folder" />
        <br />
        <br />
        <asp:Label ID="lblMsg" runat="server" ForeColor="Green" Text=""></asp:Label>
        <br />
        <h2 style="text-decoration: underline; font-weight: bold; color: #0066FF;">
            Uploaded File Details
        </h2>
        <asp:GridView ID="GridViewUploadedFile" runat="server" EmptyDataText="No files found!"
            AutoGenerateColumns="False" Font-Names="Verdana" AllowPaging="true" PageSize="5"
            Width="50%" OnPageIndexChanging="GridViewUploadedFile_PageIndexChanging" BorderColor="#CCCCCC"
            BorderStyle="Solid" BorderWidth="1px">
            <AlternatingRowStyle BackColor="#FFD4BA" />
            <HeaderStyle Height="30px" BackColor="#FF9E66" Font-Size="15px" BorderColor="#CCCCCC"
                BorderStyle="Solid" BorderWidth="1px" />
            <RowStyle Height="20px" Font-Size="13px" BorderColor="#CCCCCC" BorderStyle="Solid"
                BorderWidth="1px" />
            <Columns>
                <asp:BoundField DataField="rowid" HeaderText="#" HeaderStyle-Width="10%" />
                <asp:TemplateField HeaderText="List of Files" HeaderStyle-Width="90%">
                    <ItemTemplate>
                        <asp:HyperLink ID="HyperLink1" Target="_blank" runat="server" Text='<%# Eval("filenameName") %>'
                            NavigateUrl='<%# Eval("filePath") %>'>
                        </asp:HyperLink>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>

Web.config part

this will enable you to upload any size of pdf file on server
<httpRuntime
      executionTimeout="999999"
      maxRequestLength="2097151"
      useFullyQualifiedRedirectUrl="false"
      minFreeThreads="8"
      minLocalRequestFreeThreads="4"
      appRequestQueueLimit="100"
      enableVersionHeader="true"/>

In our project solution there is a folder name as Userfiles where we going to upload/save User uploaded file. For thar purpose we create a 'key' in our web.config folder
<appSettings>
<add key="FilePath" value=""/>
</appSettings>

Coding Part


1. Upload Button Click Event
//Here we are setting value of key which we create in Web.config file and it will use for set the path where we want to save/upload our pdf file

//TextBox1.Text --> I am using formal TextBox field for creating subfolder in our Userfiles folder
ConfigurationManager.AppSettings["FilePath"] = "~/Userfiles/"
+ TextBox1.Text.Trim()+"/";
           
string GettingNewFilePath = ConfigurationManager.AppSettings["FilePath"].ToString();
           
string directoryPath = Server.MapPath(string.Format("" + FilePath + "/{0}/", TextBox1.Text.Trim()));
           
// Check wheather folder is already exist or not
if (!Directory.Exists(directoryPath))
{
       Directory.CreateDirectory(directoryPath);
       ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Folder Created.');", true);
       }
else
{
       ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Directory already exists.');", true);
       }

bool blSucces = false;
       string filename = string.Empty;
       //To check whether file is selected or not to uplaod
       if (FileUploadToServer.HasFile)
       {
       try
       {
       string[] allowdFile = { ".pdf" };
       //Here we are allowing only pdf file so verifying selected file pdf or not
       string FileExt = System.IO.Path.GetExtension(FileUploadToServer.PostedFile.FileName);
                    bool isValidFile = allowdFile.Contains(FileExt);
        if (!isValidFile)
              {
              lblMsg.ForeColor = System.Drawing.Color.Red;
              lblMsg.Text = "Please upload only pdf ";
              }
              else
              {
//Get file name of selected file
              filename = Path.GetFileName(FileUploadToServer.FileName);
              //Save selected file into specified location
                        FileUploadToServer.SaveAs(Server.MapPath(GettingNewFilePath) + filename);
       lblMsg.Text = "File upload successfully!";
       blSucces = true;

        }
}
       catch (Exception ex)
       {
       lblMsg.Text = "Error occurred while uploading a file: " + ex.Message;
       }
}
else
{
lblMsg.Text ="Please select a file to upload.";
}
//Store file details into database
if (blSucces)
{
Updatefileinfo(filename, GettingNewFilePath + filename);
}

2. Method for saving detail in SQL Database
using (SqlConnection Sqlcon = new SqlConnection(strCon))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    Sqlcon.Open();
                    cmd.Connection = Sqlcon;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "SP_FileUpload";

                    cmd.Parameters.Add(new SqlParameter("@pvchAction", SqlDbType.VarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@pvchFileName", SqlDbType.VarChar, 100));
                    cmd.Parameters.Add(new SqlParameter("@pvchFilepath", SqlDbType.VarChar, 100));
                    cmd.Parameters.Add(new SqlParameter("@pvchCreatedBy", SqlDbType.VarChar, 100));
                    cmd.Parameters.Add("@pIntErrDescOut", SqlDbType.Int).Direction = ParameterDirection.Output;

                    cmd.Parameters["@pvchAction"].Value = "insert";
                    cmd.Parameters["@pvchFileName"].Value = strfilename;
                    cmd.Parameters["@pvchFilepath"].Value = strPath;
                    cmd.Parameters["@pvchCreatedBy"].Value = "Admin";
                    cmd.ExecuteNonQuery();
                    int retVal = (int)cmd.Parameters["@pIntErrDescOut"].Value;
                }
            }
            //Display complete uploaded file details in gridview
            LoadData();