Download .dat file from server - c#

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

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 file from url and manage download count in 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();
}

FolderBrowserDialog does not open on IIS [duplicate]

I've been searching around the internet, but couldn't find any useful answer.
I have an ASP.NET web site, which is deployed on server.
The ASP.NET web site on the server can access a directory called W:/ .
The clients in the company can access the web site. The web site lists in a ListBox all the PDF files from the W:/ directory. The client should be able to select PDF files from the listbox and save them to it's local PC by selecting a location for it.
Something like save as file on web pages.
Could you provide me some solution or work around ?
Finally I've found an article, which Prompts a Save Dialog Box to Download a File from ASP.NET
I post it here, might help somebody else as well and save some time.
String FileName = "FileName.txt";
String FilePath = "C:/...."; //Replace this
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
This is an extension to user1734609's solution that gets a file locally.
To download a file from the server to client:
public void DownloadFile()
{
String FileName = "201604112318571964-sample2.txt";
String FilePath = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/Uploads/" + FileName;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
}
The correct keywords are "File Browser asp.net" to find a lot of examples with source code.
Here is one from codeproject:
http://www.codeproject.com/Articles/301328/ASP-NETUser-Control-File-Browser
Get file contents in byte[] from W drive and write it to local file.
byte[] data = File.ReadAllBytes(WDriveFilePath)
FileStream file = File.Create(HttpContext.Current.Server.MapPath(MyLocalFile));
file.Write(data, 0, data.Length);
file.Close();
I have done something like this to get the file .
protected void btnExportFile_Click(object sender, EventArgs e)
{
try
{
Thread newThread = new Thread(new ThreadStart(ThreadMethod));
newThread.SetApartmentState(ApartmentState.STA);
newThread.Start();
// try using threads as you will get a Current thread must be set to single thread apartment (STA) mode before OLE Exception .
}
catch (Exception ex)
{
}
}
static void ThreadMethod()
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}

HttpResponse Transmit File - stopping following code

I have an asp.net button which calls this method.
protected void DownloadFile(object sender, EventArgs e)
{
Response.Clear();
string filePath = getFilePath();
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=FvGReport.xlsx");
Response.TransmitFile(filePath);
Response.End();
newReportMessage.Visible = false;
}
But the newReportMessage.Visible component is never able to run. Through reading around I could see that Response.End() just terminates the thread and so that made sense. So I have tried what seems to work for a lot of other people.
protected void DownloadFile(object sender, EventArgs e)
{
Response.Clear();
string filePath = getFilePath();
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=FvGReport.xlsx");
Response.TransmitFile(filePath);
Response.Flush();
Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
newReportMessage.Visible = false;
}
But it still doesn't work? Does anyone know what the problem is so I can avoid this in the future, and what is the solution?

asp.net let user download file with save dialog

I am having some problems with downloading files with the save dialog.
My code executes with no errors but no save dialog shows up. Not in FF, not in chrome and not in IE. The attachment can have the following extensions: .jpg,.jpeg,.png,.bmp,.pdf,.txt,.docx. That's why I use Response.ContentType = "application/octet-stream"; (see in code below).
protected void btnDownload_OnCommand(object sender, CommandEventArgs e)
{
//Get the attachment to download from the webservice
RCX.AddressAttachment attachment = ShopClient.GetAddressAttachment(ServiceContext,
new AddressAttachmentCriteria()
{
Id = (string) e.CommandArgument //= AttachmentID
});
//Get a random filename
var fileName = string.Format("{0}{1}", Guid.NewGuid(), attachment.FileExtension);
//Get the physicalPath to save the file
var physicalPath = string.Format(#"{0}\Attachments\{1}", System.AppDomain.CurrentDomain.BaseDirectory,
fileName);
//Get the webpath to navigate to the file
var webPath = string.Format("{0}Attachments/{1}", Misc.BaseUrl(Request.Url), fileName);
//Create file if not exists
using (new FileStream(physicalPath, FileMode.OpenOrCreate))
{
}
//Write bytes to file
System.IO.File.WriteAllBytes(physicalPath, attachment.Attachment);
var fileInfo = new FileInfo(physicalPath);
//Try to open the save dialog, what is wrong here?
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0};", fileName));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.WriteFile(physicalPath);
Response.End();
}
The file exists after executing the WriteAllBytes(string path, byte[] bytearray) method.
If I navigate to the webPath in my code, I can also see the file in the browser (see code below).
Response.Redirect(webPath);
What could I be doing wrong?
Many thanks.
Try this
Response.Flush();
before the Response.End();

Categories

Resources