Download xml with its xsl file - asp.net

I want to download xml file along with xsl(stylesheet).
My code for downloading xml file is as below:
XPathDocument myXPathDoc = new XPathDocument("myxml.xml");
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load("myxsl.xsl");
XmlTextWriter myWriter = new XmlTextWriter("Result.html", null);
myXslTrans.Transform(myXPathDoc, null, myWriter);
string strFullPath = Server.MapPath("Result.html");
string strContents = null;
System.IO.StreamReader objReader = default(System.IO.StreamReader);
objReader = new System.IO.StreamReader(strFullPath);
strContents = objReader.ReadToEnd();
objReader.Close();
//attach that XML file and download on local machine
string attachment = "attachment; filename=" + myWriter;
Response.ClearContent();
Response.ContentType = "text/html";
Response.AddHeader("content-disposition", attachment);
Response.Write(strContents);
I have searched in google, but not able to find a solution. Give some idea regarding this
But its giving exception like
The process cannot access the file '~mypath\Result.html' because it is being used by another process.

Do you want to write the xml to the response, or the xml with the xsl applied to it? If it is the latter, check this link:
Applying XSLT to XML in C#
If you want to just return the raw XML, then your code seems to be doing that already. However, the title of your question is a little misleading because you indicate you want to download 2 files with 2 request, which may be done with MIME but I fail to see the use of this. If a client is requesting an XML and XSL file, why not just apply them together?

I have added one html file and done like below
string strFullPathXml = Server.MapPath("myxml.xml");
string strFullPathXsl = Server.MapPath("myxsl.xsl");
string strFullPathHtml = Server.MapPath("Result.html");
XPathDocument xPathDoc = new XPathDocument(strFullPathXml);
XslCompiledTransform xslTrans = new XslCompiledTransform();
xslTrans.Load(strFullPathXsl);
XmlTextWriter xWriter = new XmlTextWriter(strFullPathHtml, null);
xslTrans.Transform(xPathDoc, null, xWriter);
xWriter.Close();
Response.ContentType = "text/html";
Response.AppendHeader("Content-Disposition", "attachment; filename=Result.html");
Response.ClearContent();
Response.WriteFile(strFullPathHtml);
Response.Flush();
Response.End();
After that its downloading html file which is in human readable format.

Related

How to write the context of a FileStream to my ASP.net HTTP Response?

Suppose that I want my ASP.net web server to open a file and then send it to the browser.
First, I write this:
FileInfo file = new System.IO.FileInfo(#"\\myshare\myfile.zip");
FileStream fileStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
What comes next?
I would think something along the lines of Response.Write(..., but I'm having trouble figuring it out.
straight from MSDN:
HttpResponse.BinaryWrite Method
FileStream MyFileStream;
long FileSize;
MyFileStream = new FileStream("sometext.txt", FileMode.Open);
FileSize = MyFileStream.Length;
byte[] Buffer = new byte[(int)FileSize];
MyFileStream.Read(Buffer, 0, (int)FileSize);
MyFileStream.Close();
Response.Write("<b>File Contents: </b>");
Response.BinaryWrite(Buffer);
Edit: of course there are also many other methods, like streaming which allows you to never allocate the byte[] buffer all at once on the web server. This was just a starting point...
A good way to send files is using the content-disposition header before you send the actual raw data
for instance:
Response.ContentType = "application/jpeg";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.WriteFile(path);
Response.End();
where fileName is just the filename (with extension)
and path is the full path to the file

ASP.Net page export to pdf

I got stuck with my ASP.Net export to PDF. Below are my codes. Please help.
Response.Clear();
Response.Buffer = true;
Response.Charset = Encoding.UTF8.HeaderName;
Response.ContentEncoding = Encoding.UTF8;
Response.Write(string.Format("<meta http-equiv=Content-Type content=text/html;charset={0}>", Encoding.UTF8.HeaderName));
Response.ContentType = "application/pdf";
Response.Headers.Add("Content-disposition", "attachment; filename=pdffilename.pdf");
StringBuilder sb = new StringBuilder();
sb.Append("MIME-Version: 1.0\r\n");
sb.Append("X-Document-Type: Worksheet\r\n");
sb.Append("Content-Type: multipart/related; boundary=\"----=mtrSystem\"\r\n\r\n\r\n");
sb.Append("------=mtrSystem\r\n");
sb.Append("Content-Type: text/html; charset=\"utf-8\"\r\n");
sb.Append("<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n");
sb.Append("xmlns:x=\"urn:schemas-microsoft-com:office:pdf\">\r\n\r\n\r\n");
sb.Append("------=mtrSystem\r\n");
sb.Append("Content-ID: baiduimg\r\n");
sb.Append("Content-Transfer-Encoding: base64\r\n");
sb.Append("Content-Type: image/png\r\n\r\n");
Can i use this way to export my ASP.Net page to PDF?
Html-to-pdf.net allows for converting html to pdf. TO get the html from an asp.net page, use the following code:
StringWriter sw = new StringWriter();
Server.Execute("PageToConvert.aspx", sw);
string htmlCodeToConvert = sw.GetStringBuilder().ToString();
Then pass the html to the pdf generator:
public byte[] GetPdfBytesFromHtmlString (string htmlString)
You can then save the bytes to the response to send to client, or save on the server as a local file.
EDIT:
Something to keep in mind, html-to-pdf does cost money, but for my last project it was a justified expense. You can use the trial version to figure out what you needd.
I'm not entirely sure what you're trying to do, but generally I can highly recommend PDFSharp for creating PDF documents in code...

How do I create an XML file with ASP.NET and have it prompt to download?

I'm currently trying to write data (client machine) into a xml file where the user can save. However, I want the users to be able to decide on where they want to save this written xml file. Is there any controls or codes that I can use to allow the users to save the file?.
Update:
is that right way to do?
**HttpContext.Current.Response.Write(xw.ToStroing()); <<< ??????**
HttpContext.Current.Response.End();
update:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
MemoryStream ms = new MemoryStream();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "text/xml";
HttpContext.Current.Response.AddHeader("Content-Disposition:", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
using (StringWriter sw = new StringWriter())
{
using (XmlWriter xw = XmlWriter.Create(ms, settings))
{
xw.WriteStartDocument();
xw.WriteStartElement("Name");
xw.WriteStartElement("Application");
................
......................
HttpContext.Current.Response.Write(xw.ToStroing());
HttpContext.Current.Response.End();
When you begin a file download, the client's browser will handle the file saving location.
If you want to force the file to download instead of open, add this HTTP header to your response:
Content-Disposition: attachment; filename="myFile.xml"
here is the link helps me :)
Where is the MemoryStream being used? You should pass the StringWriter to the XmlTextWriter constructor then Response.Write() the contents of the StringWriter
Add this after the Response.AddHeader line:
Response.ContentType = "application/octet-stream";
This will force download of files, regardless the file type.

when i try to save this file it creates and folder for the entire path

ZipFileToCreate = "c:\user\desktop\webservice\file.zip";
So, when i try to save this file it creates the folder for the path like user\desktop\webservice\file\
Why is it so?
FileStream fs = new FileStream(ZipFileToCreate, FileMode.Open);
byte[] data = new Byte[fs.Length];
BinaryReader br = new BinaryReader(fs);
br.Read(data, 0, data.Length);
br.Close();
Response.Clear();
Response.ContentType = "application/x-zip-compressed";
Response.AppendHeader("Content-Disposition", "filename=" + Parameter + ".zip");
DeleteOldFiles();
Response.BinaryWrite(data);
I think you need to be using the Environment.GetFolderPath method to find the current users' Desktop folder rather than hard-coding "c:\user\desktop\webservice\file.zip". Also using Path.Combine to build a path is more reliable than string concatenation. Try
Parameter = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "file.zip");

ASP.NET stream content from memory and not from file

The users have requested the option to "download" a csv file representation of GridView contents. Does anyone know how to do this without saving the file to the server but rather just streaming it to the user from memory?
Thanks
Implement an IHttpHandler.
I used something similar to the following in the ProcessResponse for outputing a CSV that had previously been constructed in a database table...
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
//Get data to output here...
//Turn off Caching and enforce a content type that will prompt to download/save.
response.AddHeader("Connection", "close");
response.AddHeader("Cache-Control", "private");
response.ContentType = "application/octect-stream";
//Give the browser a hint at the name of the file.
response.AddHeader("content-disposition", string.Format("attachment; filename={0}", _filename));
//Output the CSV here...
foreach(BatchDTO.BatchRecordsRow row in dtoBatch.BatchRecords)
response.Output.WriteLine(row.Data);
response.Flush();
response.Close();
}
There are a number of libraries that make generating a CSV easier, you should just be able to pass it the Response.OutputStream to have it write to there rather than to a file stream.
Use context.Response.OutputStream.
Here's an example.
I created a StringBuilder and dump the contents to the Response object using the following code ("csv" is the StringBuilder variable).
Response.ContentType = #"application/x-msdownload";
Response.AppendHeader("content-disposition", "attachment; filename=" + FILE_NAME);
Response.Write(csv.ToString());
Response.Flush();
Response.End();
I have used the RKLib export library a few times to great effect, this uses a memory stream and can be given any datatable which it will export as a csv download:
http://www.codeproject.com/KB/aspnet/ExportClassLibrary.aspx

Resources