Saving Exported doc file to the disk - c#

Is it possible to save an exported word document file using Response.Write(). Now it's showing Save/Open dialog box, once it Converted successfully. But i need to save this file to a folder. Please help me for resolve this issue.
My conversion to Doc code is appended below.
private void ExportDataSetToWordDoc()
{
try
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", DateTime.Today.ToShortDateString().Replace("/", "").Replace("-", "") + "_" + DateTime.Now.ToShortDateString() + ".doc"));
Response.ContentType = "application/ms-word";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
tblMain.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
catch (ThreadAbortException ex)
{
Common.LogError(ex);
}
}

It's up to the Browser to offer the user an "open or save" option. That's what your content-disposition "attach" is encouraging the browser to do. Your other option is content-disposition "inline", where the browser will usually just call up the application (Word in this case) to open the file. See MSDN.
Sadly, the browser will not always offer the filename you specified as the default filename in the "Save As" dialog. Often it will offer the name of your web page as the default instead. Firefox at least documents this as a bug, IE seems to think it is a "feature".

I have modified my code as shown below. Now its saving the specified folder
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", DateTime.Today.ToShortDateString().Replace("/", "").Replace("-", "") + "_" + DateTime.Now.ToShortDateString() + ".doc"));
Response.ContentType = "application/ms-word";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
tblMain.RenderControl(htw);
string strPath = Request.PhysicalApplicationPath + "Test.doc";
StreamWriter sWriter = new StreamWriter(strPath);
sWriter.Write(sw.ToString());
sWriter.Close();
Thanks.

You can use a stream writer (System.IO.StreamWriter) using a path.
When the stream writer will be closed, the file will be saved on at the specified path.
But, it will save on the server disk. If you want to save on the client side, you don't have other choice than ask the user where to put the file. You can't save files on a client without its approval.
var x = new System.IO.StreamWriter(path);
x.Close();

Related

ASP .Net C# - Get File location after downloaded

I'm currently developing a simple program (using ASP.Net C#) to populate data from GridView into Excel file. the Excel file will be need to downloaded into client computer.
For some reasons, I need to manipulate the Excel file quickly after it downloaded into client local computer.
The problem is I can't get the file location where the file was downloaded.
How can I get the file location after it downloaded into client computer ?
This is the screenshot:
Download Code:
private void Create_ExcelContent2()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=" + ddlBatchID.Text + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw); ...
gvBatchSummary.RenderControl(hw);
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
The short answer to this is you cannot do it. Once the file is on the local machine server side code cannot be use to manipulate it. If you could the security implications would be a mine field.
why don't you try as below
string folderPath = string.Empty;
using (FolderBrowserDialog fdb = new FolderBrowserDialog()) {
if (fdb.ShowDialog() == DialogResult.OK ){
folderPath = fdb.SelectedPath;
}
}
sorry i didn't seen it #fubo ,
Edit:
if at all you want that directory path, then why don't you save it to a prefixed local system path, and from there you can read it and manipulate it.

Opening a document in PDF as opposed to Word with code on a button click

I have copied code previously used throughout the system i am working on. However this code opens the content in a word document. I am looking it to be opened in a PDF.
I have already tried changing the string declaration 'filename' to end in (.pdf) as opposed to (.doc) but when attempting to open it it says "could not open the document because it is either not a spported file type or because the file has been damaged....".
What changes need to be made to this code in order to open it as an adope pdf. I wouldnt imagine it would be alot.
string content = sw.GetStringBuilder().ToString();
string fileName = "IRPBestPracticeArticle.doc";
Response.AppendHeader("Content-Type", "application/msword; charset=utf-8");
Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
Response.Charset = "utf-8";
Response.Write(content);
I cannot say for certain, but I am going to assume you're trying to save your data as a pdf and have it open in whatever application the system uses to read pdf files?
//Note the change from application/msword to application/pdf
Response.AppendHeader("Content-Type", "application/pdf; charset=utf-8");
Make sure to change the mime type as well as the doc ending (See here for full list of mime types):
That being said, I cant guarantee it will open properly in your PDF reader
Just try this set of code.
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=" + fileName);
Response.ContentType = "application/pdf";
Response.WriteFile("FullFilePath");
Response.Flush();
Response.Clear();
Response.End();
The mime type need to be set correctly before opening the file.
Andy try this one. You must have ItextSharp.dll to use this code. Download it from here. Then add its reference in your page.
try this code to create pdf from string and download it
Document document = new Document(PageSize.A4);
using (MemoryStream ms = new MemoryStream())
{
PdfWriter.GetInstance(document, ms);
document.Open();
System.Xml.XmlTextReader _xmlr;
if (String.IsNullOrEmpty(errorMsg))
_xmlr = new System.Xml.XmlTextReader(new StringReader(GetTransferedData(content)));
else
_xmlr = new System.Xml.XmlTextReader(new StringReader(#"<html><body>Error Message:" + errorMsg + "</body></html>"));
iTextSharp.text.html.HtmlParser.Parse(document, _xmlr);
document.Close();
ms.Flush();
byte[] data = ms.ToArray();
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.BinaryWrite(data);
Response.End();
ms.Close();
}
First, convert the .doc files to PDF files. Here is a sample of how to achieve this: Convert Doc file to PDF in VB.Net
After you have the PDF files, stream them to the browser using the "application/pdf" content type.

Open document with word, without path

I'm searching how to open a document with word, without its path.
I get my document like this :
byte[] text = item.Doc;
The document comes directly from database.
I only found way to open with a path... So with my doc, I must open it, and then run saveAs of word application (choice between pdf, doc etc...).
I can store it in a MemoryStream, but, what can I do with it next?
Found this How to open a file from Memory Stream, but not helping me.
try this
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/ms-word";
string fileName = "Test.doc";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
StreamReader reader = new StreamReader(memoryStream, System.Text.Encoding.UTF8, true);
string strContents = reader.ReadToEnd();
Reader.Close();
Response.Write(strContents);
Response.End();
--SJ

Export page to excel with logo image

I have to export some data from an asp.net page to excel, so I use basically a table to create the custom headers I need then a GridView. All the data displays correctly when exported to excel, but when I added an Logo image to the html, it doesn't show up on the Excel file when exported.
Since I need to export it to Excel 2007 or later, I know I can use the Open XML stuff from Microsoft to export the data, the problem is that I already have everything done on the code and I wanted to know if there is another way to do that instead of doing all over again using Open XML.
If there isn't a way to do that without using Open XML, can anyone show me how I could export the data to it? I tried once but I didn't have much success. =/
BTW, I'm using C#.
Thanks in advance!
I've updated the code and now it looks like this, but I still can't see the image... =/
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
frmPlanoAcao.RenderControl(htmlWrite);
StringWriter w = new StringWriter();
HtmlTextWriter t = new HtmlTextWriter(w);
imgLogo.RenderControl(t);
var byte_array = System.Text.Encoding.ASCII.GetBytes(w.ToString());
Response.Write(stringWrite.ToString());
this.EnableViewState = false;
Response.Clear();
Response.Buffer = false;
Response.Charset = "ISO-8859-1";
Response.ContentEncoding = System.Text.Encoding.GetEncoding(1252);
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "plano_acao.xls"));
Response.ContentType = "application/vnd.ms-excel";
Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
Response.Write(getExcelStyling());
Response.OutputStream.Write(byte_array, 0, byte_array.Length);
Response.Write(stringWrite.ToString());
Response.Write("</body>");
Response.Write("</html>");
Response.End();
Try the following code. I have tested at local IIS and it is working properly.
Including the image like Header Image/Logo on top of the grid data.
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;");
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
dgrExport.DataSource = dtExport;
dgrExport.DataBind();
dgrExport.RenderControl(htmlWrite);
string headerTable = #"<Table><tr><td><img src=""D:\\Folder\\1.jpg"" \></td></tr></Table>";
Response.Write(headerTable);
Response.Write(stringWrite.ToString());
Response.End();
you can customize your image's height and width as per your requirement. Same height and width setting will be required for the <TD> tag.
You have to get images in StringWriter and use System.Text.Encoding.ASCII.GetBytes(stringwriter string) in array of bytes.
then write these as outputStream.Write(byte_array, 0, byte_array.Length);
where outputstream is HttpContext Response outputstream.
If you say, to convert Grid, Images, everything in one go to Excel, i have not tried. But, i can say, you can individually have both of them into Excel by their way.
If you are using C# and want to export to Excel I would recommend EPPLUS
http://epplus.codeplex.com/
Will save you a whole lot of troubles now and in the future.

Create text file and download

I'm trying to write to a text file in memory and then download that file without saving the file to the hard disk. I'm using the StringWriter to write the contents:
StringWriter oStringWriter = new StringWriter();
oStringWriter.Write("This is the content");
How do I then download this file?
EDIT:
It was combination of answers which gave me my solution. Here it is:
StringWriter oStringWriter = new StringWriter();
oStringWriter.WriteLine("Line 1");
Response.ContentType = "text/plain";
Response.AddHeader("content-disposition", "attachment;filename=" + string.Format("members-{0}.csv",string.Format("{0:ddMMyyyy}",DateTime.Today)));
Response.Clear();
using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8))
{
writer.Write(oStringWriter.ToString());
}
Response.End();
This solved for me:
MemoryStream ms = new MemoryStream();
TextWriter tw = new StreamWriter(ms);
tw.WriteLine("Line 1");
tw.WriteLine("Line 2");
tw.WriteLine("Line 3");
tw.Flush();
byte[] bytes = ms.ToArray();
ms.Close();
Response.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition", "attachment; filename=file.txt");
Response.BinaryWrite(bytes);
Response.End();
Instead of storing the data in memory and then sending it to the response stream, you can write it directly to the response stream:
using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8)) {
writer.Write("This is the content");
}
The example uses the UTF-8 encoding, you should change that if you are using some other encoding.
Basically you create an HttpHandler by implementing the IHttpHandler interface. In the ProcessRequest method you basically just write your text to context.Response. You also need to add a Content-Disposition http header:
context.Response.AddHeader("Content-Disposition", "attachment; filename=YourFileName.txt");
Also remember to set the ContentType:
context.Response.ContentType = "text/plain";
Just a small addition to the other answers. At the very end of a download I execute:
context.Response.Flush();
context.ApplicationInstance.CompleteRequest();
I learned that otherwise, the download sometimes does not complete successfully.
This Google Groups posting also notes that Response.End throws a ThreadAbortException which you could avoid by using the CompleteRequest method.
I had many issues with this. Finnaly found a solution that seems to work everytime.
In most cases the user is going to click a button for the download. At this point it is best to redirect the page back to the same spot. add a parameter in the url that you can grab and read.
example( www.somewhere.com/mypage.aspx?print=stuff)
<asp:Button ID="btn" runat="server" Text="print something" OnClick="btn_Click" />
protected void Page_Load(object sender, EventArgs e) {
if (Request["print"] == "stuff") { Print("my test content"); }
}
/* or pass byte[] content*/
private void Print(string content ){
Response.ContentType = "text/plain";
Response.AddHeader("content-disposition", "attachment;filename=myFile.txt");
// Response.BinaryWrite(content);
Response.Write(content);
Response.Flush();
Response.End();
}
protected void btn_Click(object sender, EventArgs e) {
// postbacks give you troubles if using async.
// Will give an error when Response.End() is called.
Response.Redirect(Request.Url + "?print=queue");
}
Extension of #Vinicious answer.
I had data that could contain commas. The common solution is to escape that piece of data by enclosing it in quotes, while making sure to also escape quotes that could also be a part of the data.
One rub I came against and a warning when writing CSV, excel will not like you if you put spaces trailing your commas. discovered solution to my problem from superuser answer
protected void btnDownload_Click(object sender, EventArgs e)
{
MemoryStream ms = new MemoryStream();
TextWriter tw = new StreamWriter(ms, System.Text.Encoding.UTF8);
var structures = KAWSLib.BusinessLayer.Structure.GetStructuresInService();
// *** comma delimited
tw.Write("Latitude, Longitude, CountySerial, StructureType, Orientation, District, RoutePre, RouteNo, LocationDesc");
foreach (var s in structures)
{
tw.Write(Environment.NewLine + string.Format("{0:#.000000},{1:#.000000},{2},{3},{4},{5},{6},{7},{8}", s.LATITUDE, s.LONGITUDE, s.CO_SER, EscapeIfNeeded(s.SuperTypeLookup.SHORTDESC), EscapeIfNeeded(s.OrientationLookup.SHORTDESC), s.DISTRICT, s.ROUTE_PREFIX, s.RouteValue, EscapeIfNeeded(s.LOC_DESC)));
}
tw.Flush();
byte[] bytes = ms.ToArray();
ms.Close();
Response.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition", "attachment; filename=" + string.Format("kaws-structures-{0:yyyy.MM.dd}.csv", DateTime.Today));
Response.BinaryWrite(bytes);
Response.End();
}
string EscapeIfNeeded(string s)
{
if (s.Contains(","))
{
return "\"" + s.Replace("\"", "\"\"") + "\"";
}
else
{
return s;
}
}
Below will cause a problem for excel. In excel the first quote will become part of the data and consequently than separate at the embedded comma. Spaces bad.
tw.Write(Environment.NewLine + string.Format("{0:#.000000}, {1:#.000000}, {2}, {3}, {4}, {5}, {6}, {7}, {8}", s.LATITUDE, s.LONGITUDE, s.CO_SER, EscapeIfNeeded(s.SuperTypeLookup.SHORTDESC), EscapeIfNeeded(s.OrientationLookup.SHORTDESC), s.DISTRICT, s.ROUTE_PREFIX, s.RouteValue, EscapeIfNeeded(s.LOC_DESC)));
This is very simple, and the answer can be seen in this Microsoft KB Article: How to write binary files to the browser using ASP.NET and C#

Categories

Resources