Download a file in C#

Asked

Viewed 180 times

-1

Good Afternoon, I’m a beginner in C# and I’ve already looked for this answer here on the internet and I didn’t find it at all, I’m working with C# and windows Forms, I have a folder inside my application called img and I have a pdf file inside it, I would like when the customer clicks on the button he downloads that pdf file to the client’s computer downloads folder. How can I do that? I’ve tried everything and I can’t.

  //Baixar Pdf
        private void toolStripButton11_Click(object sender, EventArgs e)
        {
            
                this.DownloadFile("img\\Ajuda.pdf", "Ajuda.pdf");
         }

2 answers

1


Actually you don’t have to download, you need to copy the file to the folder Downloads. This code will help you:

    string finalPath = Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads\\Ajuda.pdf");
    System.IO.File.Copy("img\\Ajuda.pdf", finalPath);

Methods used:
File.Copy
Path.Combine
Environment.Getfolderpath

  • mto thanks, this solution already solves my problem.

  • you could tell me how I do to check if the file already exists in the download folder?

  • @Joana Use o File.Exists https://docs.microsoft.com/en-us/dotnet/api/system.io.file.exists?view=net-5.0

  • I used as the code shows, but as my folder is "Donwloads" and does not have the C: in front it does not recognize the folder...

  • @Joana final adjustmentPath as needed. See: https://www.codeproject.com/Articles/878605/Getting-all-Special-Folders-in-NET

  • 1

    Valew got now with this last tip, mto thanks msm :)

Show 1 more comment

0

I found a code in Stack Overflow (English) for what you want to do. It’s a little different, but it’s for the same need.

    protected void btnUpload_Click(object sender, EventArgs e)
    {
      if(string.IsNullOrEmpty(txtName.Text)) return;            
       Response.ContentType = "application/octet-stream";
       Response.AppendHeader("Content-Disposition", "attachment;filename=" + txtName.Text);
       string filePath = Server.MapPath(Path.Combine("~/SavedFolder/PDF", txtName.Text));
       Response.TransmitFile(filePath);
       Response.End();
    }

Source: https://stackoverflow.com/questions/24402035/how-to-download-pdf-file-from-files-on-button-click

  • mto thanks for the attention, I tried to use the answer above, but it keeps appearing that "Response does not exist in the current context" and that "Server does not exist in the current context", and neither appears any suggestion of Assembly .

  • This article can help with this problem https://stackoverflow.com/questions/56018968/the-name-response-does-not-exist-in-the-current-context

  • thanks for trying to help me, but the solution of the Isaque worked for me, mto obrigado.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.