How to call the server map path filename that generated randomly

Sunny 20 Reputation points
2023-02-06T17:34:11.35+00:00

This is a C# code for a Web Form page named "upload.aspx" which allows the user to upload a PDF file and store it in the server. The file uploaded must be a PDF file, and all the text boxes must be filled before submission. The file name is saved in the database as a string with the format of "GUID.pdf", Guid.NewGuid().ToString().

UPLOAD.ASPX.CS

 tTR.FileName = Guid.NewGuid().ToString() + ".pdf";
        dataBaseDataContext.TTRs.InsertOnSubmit(tTR);
        dataBaseDataContext.SubmitChanges();
        String path = Server.MapPath("Attachments/" + tTR.FileName);
        FileUploadtoServer.SaveAs(path);       

i created a search function that allows the user to search for based on Heat Code, Item Code, PO Number, and Description. user can also edit and download the file by clicking on the "Edit / Download" link. The problem here is in my Download button. It's not downloading/ able to read the path. i can see the pdf exist in the Attachment folder but it's not able to find the correct file name associated to the heat code.

public partial class track : System.Web.UI.Page
{
    DataBaseDataContext dataBaseDataContext = new DataBaseDataContext();
        protected void Page_Load(object sender, EventArgs e)
    {
    }
   
 private void BindData(List<MTR> Data)
    {
        try
        {
            if (Data.Count > 0)
            {
                StringBuilder append = new StringBuilder();
                foreach (MTR mTR in Data)
                {
                    string PdfGuid = mTR.FileName;
                    append.Append("<tr><td><a style=\"color:blue;\" href=\"#\" onclick=\"doPop('" + mTR.id + "');\">Edit / Download</a></td><td>" + mTR.Heat_Code + "</td><td>" + mTR.Item_Code + "</td><td>" + mTR.PO_Number + "</td><td>" + mTR.Description + "</td><td>" + mTR.Invoice_No + "</td></tr>");
                }
                tdList.InnerHtml = append.ToString();
            }
        }
        catch (Exception)
        {
        }
    }

protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
           
            string filePath = Server.MapPath("~/Attachments/" + filename + ".pdf");
           
            byte[] content = File.ReadAllBytes(filePath);
            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + filename + ".pdf");
            Response.Buffer = true;
            Response.BinaryWrite(content);
            Response.End();
        }
        catch (Exception)
        {
        }
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,288 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,306 questions
{count} votes

Accepted answer
  1. Lan Huang-MSFT 25,876 Reputation points Microsoft Vendor
    2023-02-08T05:26:20.0866667+00:00

    Hi @Sunny ,

    How did you get your filename?

    If the download is not successful, it should be that you have not obtained the correct filename.

    You can refer to the example below. upload.aspx

            <asp:TextBox ID="txtId" runat="server"></asp:TextBox>
            <br />
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <br />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />```
    
     protected void Upload(object sender, EventArgs e)
            {
                string folderPath = Server.MapPath("~/Attachments/");
                string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                string filename = Guid.NewGuid().ToString() + extension;
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }
                FileUpload1.SaveAs(folderPath + filename);
                int Id = Convert.ToInt32(txtId.Text);           
                string contentType = FileUpload1.PostedFile.ContentType;
                using (Stream fs = FileUpload1.PostedFile.InputStream)
                {
                    using (BinaryReader br = new BinaryReader(fs))
                    {
                        byte[] bytes = br.ReadBytes((Int32)fs.Length);
                        string constr = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                        using (SqlConnection con = new SqlConnection(constr))
                        {
                            string query = "insert into tblFiles(Id,Name, ContentType, Data) values (@Id ,@Name, @ContentType, @Data)";
                            using (SqlCommand cmd = new SqlCommand(query))
                            {
                                cmd.Connection = con;
                                cmd.Parameters.AddWithValue("@Id", Id);
                                cmd.Parameters.AddWithValue("@Name", filename);
                                cmd.Parameters.AddWithValue("@ContentType", contentType);
                                cmd.Parameters.AddWithValue("@Data", bytes);
                                con.Open();
                                cmd.ExecuteNonQuery();
                                con.Close();
                            }
                        }
                    }
                   
                    Response.Redirect("track.aspx");
    
                }
    
            }
    

    track.aspx

    <asp:Label ID="Label1" runat="server" Text="Id:"></asp:Label>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                 <asp:Button ID="DownloadFile" Text="DownloadFile" runat="server" OnClick="DownloadFile_Click" /> 
    
    protected void DownloadFile_Click(object sender, EventArgs e)
            {
                int id = Convert.ToInt32(TextBox1.Text);
                byte[] bytes;
                string fileName, contentType;
                string constr = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.CommandText = "select Name, Data, ContentType from tblFiles where Id=@Id";
                        cmd.Parameters.AddWithValue("@Id", id);
                        cmd.Connection = con;
                        con.Open();
                        using (SqlDataReader sdr = cmd.ExecuteReader())
                        {
                            sdr.Read();
                            bytes = (byte[])sdr["Data"];
                            contentType = sdr["ContentType"].ToString();
                            fileName = sdr["Name"].ToString();
                        }
                        con.Close();
                    }
                }         
                string filePath = Server.MapPath(string.Format("~/Attachments/{0}", fileName));
                byte[] content = File.ReadAllBytes(filePath);
                Response.ContentType = "application/pdf";
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
                Response.BinaryWrite(content);
                Response.Flush();
                Response.End();
            }
    

    enter image description here

    Best regards,

    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful