简体   繁体   中英

Save file in Web Application to local directory via a save dialog

I have the following code:

    public static string ExportToXML(DataSet dts, string Filename)
    {
        string returnmsg = "";

        try
        {

            dts.WriteXml(Filename, System.Data.XmlWriteMode.IgnoreSchema);
        }
        catch (Exception err)
        {
            returnmsg = returnmsg + err.ToString();
        }


        return returnmsg;
    }

which will help me to convert my Dataset into a XML file. I create a button in my web application to call the above function and was expecting the following screen:

在此处输入图片说明

(of course, the Name will not be default.aspx but the filename.)

Am I missing anything in my code that cause above dialog box not appearing when I click on the button?

The first argument you pass to WriteXml , the string Filename is the name of a file that will be saved on the server .

You need to use the HttpResponse object - the WriteFile method will take the path of a file - this can be the same as the file you have written in your example code.

So, somewhere in your code behind, you should have something like the following:

ExportToXML(myDataSet, theFileName);

Response.WriteFile(theFileName);

You should transmit the file to the client.

Basically you want to

  1. Save the XML file on your server.

  2. Transmit it to the client using above method

For more information read about Response.TransmitFile .

You can call DataSet.WriteXml Method (Stream, XmlWriteMode) passing the Response.OutputStream as first parameter. You may have to call Response.Clear() before that.

dts.WriteXml(Response.OutputStream, System.Data.XmlWriteMode.IgnoreSchema); 

With the help from Yener, Oded and Blachshma,

I have modified my code as follows:

    try{
            HttpContext context = HttpContext.Current;
            context.Response.Clear();

            //dts.WriteXml(Filename, System.Data.XmlWriteMode.IgnoreSchema);
            context.Response.Write("<?xml version=\"1.0\" standalone=\"yes\"?>");
            dts.WriteXml(context.Response.OutputStream, System.Data.XmlWriteMode.IgnoreSchema);
            context.Response.ContentType = "text/xml";
            context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + Filename + ".xml");

            context.Response.End();

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM