FolderBrowserDialog does not open on IIS [duplicate] - c#

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();
}
}
}

Related

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();

How to give a downloaded file unique name

I have a C# application which saves a completed PDF file on a folder inside my site. During the operation I save two session variable to the filename and the filepath in the server:
string strFileName = "completed_pdf_" + k + ".pdf"; //k is a variable in a function for the name
Session["fileName"] = strFileName;
MessageBox.Show(Session["fileName"].toString()); //displays: completed_pdf_{name}.pdf
newFileServer = System.Environment.MachineName + #"/PDFGenerate/completed_pdf_" + k + ".pdf";
strFullPath = Path.GetFullPath("//" + newFileServer);
List<System.Web.UI.WebControls.ListItem> files = new List<System.Web.UI.WebControls.ListItem>();
files.Add(new System.Web.UI.WebControls.ListItem(strFullPath, strFullPath));
strN = files[0].ToString();
Session["pathName"] = strN;
MessageBox.Show(Session["pathName"].toString()); //displays: \\myserver\pdfgen\completed_pdf_{name}.pdf
I have a GridView which displays a LinkButton:
<asp:LinkButton ID="lnkDownload" Text = "Download" runat="server" OnClick = "DownloadFile" />
The function for the LinkButton is:
protected void DownloadFile(object sender, EventArgs e)
{
//MessageBox.Show(Session["pathName"].ToString()); //displays correctly
//MessageBox.Show(Session["fileName"].ToString()); //displays correctly
Response.Redirect("DownloadFilePDF.ashx?myvar=" + Session["pathName"].ToString() + "&myvar2=" + Session["fileName"].ToString());
}
My HTTPHandler code is this:
<%# WebHandler Language="C#" Class="DownloadFilePDF" %>
using System;
using System.Web;
public class DownloadFilePDF : IHttpHandler {
public void ProcessRequest (HttpContext context) {
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string strSessVar = request.QueryString["pathName"];
System.Web.HttpRequest request2 = System.Web.HttpContext.Current.Request;
string strSessVar2 = request.QueryString["fileName"];
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", "attachment; filename=" + strSessVar + ";");
response.End();
}
public bool IsReusable {
get {
return false;
}
}
}
When I run my website in the server itself, it asks me to download the ASHX file but if I run my website from my local PC which is on the same network as the server, it prompts me to download the PDF file. Everything is good so far, however, I am running into two issues:
The filename that is it downloading in my PC is DownloadFilePDF which is the HttpHandler filename.
The file is 0 Byte and when I open the file, it is not the right file type.
How can I fix so that..
The filename is the fileName QueryString I am sending to the HttpHandler file.
I can download the file which is residing in the server itself, so it's not 0 Byte.
How to give a downloaded file unique name
You can use couple of options, like the Guid class, DateTime.Now method and so on in order to have a unique identifier for the downloaded file, for example, use Guid.NewGuid:
response.AddHeader("Content-Disposition", "attachment; filename=" + string.format(strSessVar+{0}, Gui.NewGuid()) + ";");
UPDATE:
By using the following code you're doing nothing but sending an empty file:
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", "attachment; filename=" + strSessVar + ";");
response.End();
In order to solve it, jst stream your file content to the response, look:
response.BinaryWrite(GetFileContentsFromSomewhere());
Something is amiss here. I don't see any content being streamed to the client. You need to provide the content in the response, like this:
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", "attachment; filename=" + strSessVar + ";");
response.BinaryWrite(GetFileContentsFromSomewhere()); //<--- this baby does all the magic
response.End();
The GetFileContentsFromSomewhere() implementation depends on where you intend the file to come from. If it's just a static file on your web server, you could use something like this:
response.WriteFile(localPathOfFile);
or
response.WriteFile(Server.MapPath(urlOfFile));

SaveFileDialog does not open in production environment

I have a SaveFileDialog to save file from database.
It works fine until I host the website on IIS. Then it starts to open debugger.
Apparently the dialog gets blocked but I don't have further ideas on what I can use instead.
My code is.
SaveFileDialog save = new SaveFileDialog();
save.FileName = tbl.Rows[0][0].ToString();
if (save.ShowDialog() == DialogResult.OK && save.FileName != "")
{
FileStream FS1 = new FileStream(save.FileName, FileMode.Create);
byte[] blob = (byte[])tbl.Rows[0][1];
FS1.Write(blob, 0, blob.Length);
FS1.Close();
FS1 = null;
}
Any help would be appreciated.
I guess you are using a Windows Forms SaveFileDialog in an ASP.NET website. This is not possible. Maybe it works on you development machine since the Cassini service is running as current user.
Solution:
Write something that works for ASP.NET
String FileName = tbl.Rows[0][0].ToString();
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 + ";");
byte[] blob = File.ReadAllBytes(FilePath );
response.BinaryWrite(blob );
response.Flush();
response.End();
There is HttpContext.Current.Response.Write and HttpContext.Current.Response.BinaryWrite and client browser should handle how to save it
using System;
using System.IO;
using System.Web.UI;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
// 1.
// Get path of byte file.
string path = Server.MapPath("~/Adobe2.png");
// 2.
// Get byte array of file.
byte[] byteArray = File.ReadAllBytes(path);
// 3A.
// Write byte array with BinaryWrite.
Response.BinaryWrite(byteArray);
// 3B.
// Write with OutputStream.Write [commented out]
// Response.OutputStream.Write(byteArray, 0, byteArray.Length);
// 4.
// Set content type.
Response.ContentType = "image/png";
}
}
example from http://www.dotnetperls.com/response-binarywrite

Save dialog box to download file, Saving file from ASP.NET server to the client

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();
}
}
}

Open any file from asp.net

How can I open any file, specified by a path, in ASP.NET programatically?
I tried the snippet below but it reads the contents of the file instead of opening the file:
string fileName = #"C:\deneme.txt";
StreamReader sr = File.OpenText(fileName);
while (sr.Peek() != -1)
{
Response.Write(sr.ReadLine() + "<br>");
}
sr.Close();
I also tried the File.Open method.
You can Response.Redirect to file if you're just opeining it
or if file is being downloaded you can use the folling code;
public void DownloadFile(string fileName)
{
Response.Clear();
Response.ContentType = #"application\octet-stream";
System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(FileName));
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.Flush();
}
If you want the file to be opened on the client side,Create an HTTP Handler and set the appropriate mime type on your response before streaming it out from your handler.
for more information I ask question near to your one before.
how to open file with its application

Categories

Resources