How to download file from url and manage download count in c# - c#

I have download.aspx page. In Page_Load event i download file from url and Increase download count and store to database.
When i refresh page download count increased. if i deny to download count also increased.
I want to increase count when i save file from browser.
My code is as following
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string url = "http://localhost:5045/Documents/sample.pdf";
DownLoadFile(url);
//This is code for download counter do entry in database
SoftwareController.SoftwareDownloadHistoryEdit(0, Id, CommonController.GETMyIP(), false, "ADD");
}
}
protected void DownLoadFile(string URL)
{
System.Net.WebClient net = new System.Net.WebClient();
Response.ClearHeaders();
Response.Clear();
Response.Expires = 0;
Response.Buffer = true;
Response.AddHeader("Content-Disposition", "Attachment;FileName=");
Response.ContentType = "APPLICATION/octet-stream";
Response.BinaryWrite(net.DownloadData(URL));
Response.End();
}

Related

Solution ASP.net call method from url to view pdf

I am trying to call a method to view a PDF
I am attempting to call the method from the URL eg. /Home.aspx/ViewPDF
The ViewPDF in the url is the method in the Home.aspx file.
I am new to ASP and this has stumped me, thanks if you can provide any help
EDIT 1:
I have an asp button with this in it's click method and it works:
protected void test12_Click(object sender, EventArgs e)
{
string FilePath = Server.MapPath("/Tasks/Content/54874/dummy.pdf");
WebClient User = new WebClient();
Byte[] FileBuffer = User.DownloadData(FilePath);
if (FileBuffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", FileBuffer.Length.ToString());
Response.BinaryWrite(FileBuffer);
}
}
How would I be able to make the same thing happen from visiting /Home.aspx/ViewPDF
with /ViewPDF being a method inside the code behind of Home.aspx
I believe the method needs to be static to be able to view it from the url is there any alternative for defining the file path as Server.MapPath is not static.
I have made a test method in Home.aspx:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(object sender, EventArgs e)
{
return "test";
}
But when I visit /Home.aspx/test it just loads a version of the page with no images and slightly off css
Thanks for any help
Edit 2 / Solution:
After doing a bit of looking around on google you can easily implement MVC into web forms
https://www.davepaquette.com/archive/2013/12/30/so-you-inherited-an-asp-net-web-forms-application.aspx
From that I made a controller
public FileResult GetTaskAttatchment()
{
string ReportURL = Server.MapPath("/Tasks/Content/54874/dummy.pdf");
byte[] FileBytes = System.IO.File.ReadAllBytes(ReportURL);
return File(FileBytes, "application/pdf");
}
Which now works perfectly, Thanks again for all the help
//check your datatype for attachment shuld be varbinary...
protected void btnfinalupload_Click(object sender, EventArgs e)
{
string filename = "";
string filenameret = "";
using (DataSet ds = GetFormForDownload(id,finid))
{
if (ds.Tables[0].Rows.Count > 0)
{
filenameret = ds.Tables[0].Rows[0]["attachment"].ToString().Trim();
filename = ds.Tables[0].Rows[0]["filename"].ToString().Trim();
byte[] bytes;
string fileName, contentType;
bytes = (byte[])ds.Tables[0].Rows[0]["attachment"];
contentType = "application/pdf";
fileName = filename;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
}

How to download a file from server using its path from withing a child gridview in asp.net

I have a nested scenario with gridview and there is a requirement of downloading a file from the child gridview.
I am fetching the path but not getting an appropriate way to download the file as it has different types, like .xls,.docx,.png,.jpg etc.
here is a snip of Grid
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "AttachDownload")
{
WebClient webClient = new WebClient();
string url = e.CommandArgument.ToString();
byte[] bytes = webClient.DownloadData(url);
string fileName = e.CommandSource.ToString();
// Response.ContentType = "image/png";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.End();
// ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Download Attachment')", true);
}
}
catch (Exception ex) { lblErrorText.Text = ex.ToString(); }
}
The Row command event is fired and command argument is the file's name.

No postback after response.End() on button click

I have a problem with not getting a postback after Response.End();
So the scenario is that i will click a button, clean an xmlfile and generate a message (out msg), download the xml, and then show the message in a label on the webpage. The problem is that it doesn't do anything after Response.End().
protected void btnDoIt_Click(object sender, EventArgs e)
{
string xml = "exampleXml";
string fileName = "exampleName";
MemoryStream ms = new MemoryStream();
string msg;
var cleanXml = CleanXml(xml, out msg);
cleanXml.Save(ms);
byte[] bytes = ms.ToArray();
Response.Clear();
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xml", fileName));
Response.ContentType = "text/xml";
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
lblFeedback.Text = msg;
lblFeedback.Visible = true;
}
I tried moving the code in front of response.End(), like below, but it didn't work as well for some reason.
protected void btnDoIt_Click(object sender, EventArgs e)
{
string xml = "exampleXml";
string fileName = "exampleName";
MemoryStream ms = new MemoryStream();
string msg;
var cleanXml = CleanXml(xml, out msg);
lblFeedback.Text = msg;
lblFeedback.Visible = true;
cleanXml.Save(ms);
byte[] bytes = ms.ToArray();
Response.Clear();
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xml", fileName));
Response.ContentType = "text/xml";
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
I also tried to "Click" an invisible button to get the postback like below. Didn't work either.
protected void btnDoIt_Click(object sender, EventArgs e)
{
string xml = "exampleXml";
string fileName = "exampleName";
MemoryStream ms = new MemoryStream();
string msg;
var cleanXml = CleanXml(xml, out msg);
InvisibleButtonClick(msg)
cleanXml.Save(ms);
byte[] bytes = ms.ToArray();
Response.Clear();
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xml", fileName));
Response.ContentType = "text/xml";
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
private void InvisibleButtonClick(string msg)
{
lblXmlFeedback.Text = msg;
lblXmlFeedback.Visible = true;
InvisibleButton_OnClick(new object(), new EventArgs());
}
protected void InvisibleButton_OnClick(object sender, EventArgs e)
{
}
What am i missing here?
What you do not have understand is that the return from IIS to the browser can be one stream only.
In your case, you believe that you can send two.
What is actually happened?
A. You post back some data from the web page.
B. You return some file for download from the user.
C. There the stream end and close – nothing is going to the browser any more. So there is no way the page to refress, and there is no way the data on the page to change because you send nothing any more to the page.
How to solve this.
a) You can make a handler that download the file and you only give a link in the page, a link to the handler that download the data.
b) you can make some other page that you redirect him with the message that you like to send, and there automatically with some javascript you start downloading your file.
c) you can use ajax to download your extra data, and javascript to show any message
similar answers
What is the best way to download file from server
file download by calling .ashx page
Updating a page before initiating a download?

Download .dat file from server

I have been trying to write a code to download file from the server, the path is correct but the file isn't downloading when I click it.
The delete code works properly which looks like this:
protected void DeleteFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
File.Delete(filePath);
GenerateDownloadLinks();
}
However the download isn't starting the download (debugging runs through entire code):
protected void ButtonDownload_Click(object sender, EventArgs e)
{
string path = (sender as LinkButton).CommandArgument;
string name = Path.GetFileName(path);
string ext = Path.GetExtension(path);
HttpResponse response = HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.AddHeader("content-disposition",
"attachment; filename=" + name);
response.ContentType = "text/plain";
response.TransmitFile(path);
response.Flush();
response.End();
}
The file I am downloading is a .dat file. I tried changing and adding the configurations but with no luck
Problem was update panel related, my datalist was inside an update panel

Open a webpage then download a file C#

From a file .aspx I need to have a redirect to a webpage, open it then download a file. Following my code:
page Source.aspx
<script runat="server">
protected override void OnLoad(EventArgs e)
{
Response.Redirect("Dest.aspx?download=true");
base.OnLoad(e);
}
</script>
page Dest.aspx
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
string download= (string)Request.QueryString["download"];
if (download == "true")
{
string url = "myurl/myfile.exe";
System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();
int bufferSize = 1;
Response.ClearHeaders();
Response.ClearContent();
Response.AppendHeader("content-disposition:", #"attachment;filename=""myFileName.exe""");
Response.AppendHeader("Content-Length", objResponse.ContentLength.ToString());
Response.ContentType = "application/download";
byte[] byteBuffer = new byte[bufferSize + 1];
System.IO.MemoryStream memStrm = new System.IO.MemoryStream(byteBuffer, true);
System.IO.Stream strm = objRequest.GetResponse().GetResponseStream();
byte[] bytes = new byte[bufferSize + 1];
while (strm.Read(byteBuffer, 0, byteBuffer.Length) > 0)
{
Response.BinaryWrite(memStrm.ToArray());
Response.Flush();
}
Response.Close();
Response.End();
memStrm.Close();
memStrm.Dispose();
strm.Dispose();
}
}
</script>
Two problems now:
Calling the page "Source.aspx" the download is automacally started but the page Dest.aspx is not shown in the browser
The downloaded file is called "Dest.aspx" instead of "myFileName.exe" ads I've set with
Response.AppendHeader("content-disposition:", #"attachment;filename=""myFileName.exe""");
For your second problem Issue Try something like that
string attachment = string.Format(CultureInfo.InvariantCulture, "attachment; filename=" + sfilename + "", fi.Name);
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", attachment);
Hope it works for you.
RIght, what you need to be doing is split the process in two:
Display your page and set a redirect value in the header to automatically redirect to your download.
download your file.
the important thing to note is that you can either respond with a web page, OR with a file, not both at once.

Categories

Resources