-3

Right now I'm working with a project there I need to make a download button. All works fine, but I can only click save or save as when I want to download the file, when i click Open, nothing happens, why that?

string path = filePath.ToString();
FileInfo file = new FileInfo(path);
if (file.Exists)
{
    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
    Response.AddHeader("Content-Length", file.Length.ToString());
    Response.ContentType = "application/msword"; //octet-stream
    Response.WriteFile(file.FullName);
    Response.End();
}

Update * Not working to open only save

private void SetWordDocument()
{
    string strFileName = CleanUp(LabelFirstName.Text + "_" +
                                 LabelLastName.Text + "_" +
                                 DateTime.Now.ToString("yyyy-MM-dd") + "." + 
                                 DropDownListDownloadCv0.SelectedItem.Text);

    object fs = Server.MapPath("~/Upload/") + strFileName;

    using (var db = new knowitCVdbEntities())
    {
        var theEmpl = (from p in db.EMPLOYEES
                       where p.username == strUserName
                       select p).FirstOrDefault();

        if (theEmpl != null)
        {        
            object missing = Missing.Value;
            object start1 = 0;
            var wordApp = new ApplicationClass();
            var myDoc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);

            object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
            Range rng = myDoc.Range(ref start1, ref missing);

            try
            {
                const char newLine = (char)11;
                myDoc.SaveAs(ref fs,
                    ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing, ref missing);
            }
            finally
            {

                    myDoc.Save();

                    //myDoc.Close(ref doNotSaveChanges, ref missing, ref missing);
                   wordApp.Quit(ref doNotSaveChanges,ref missing,ref missing);

                   myDoc = null;
                   wordApp = null;

                   System.Runtime.InteropServices.Marshal.ReleaseComObject(myDoc); 

                   System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);  



                    GC.Collect();

                System.IO.Stream iStream = null;

                // Buffer to read 10K bytes in chunk:
                byte[] buffer = new Byte[10000];

                // Length of the file:
                int length;

                // Total bytes to read:
                long dataToRead;

                // Identify the file to download including its path.
                string filepath = fs.ToString();

                // Identify the file name.
                string filename = System.IO.Path.GetFileName(filepath);

                try
                {
                    // Open the file.
                    iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                        System.IO.FileAccess.Read, System.IO.FileShare.Read);

                    // Total bytes to read:
                    dataToRead = iStream.Length;

                    Response.ContentType = "application/msword";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
                    //application/octet-stream
                    // Read the bytes.
                    while (dataToRead > 0)
                    {
                        // Verify that the client is connected.
                        if (Response.IsClientConnected)
                        {
                            // Read the data in buffer.
                            length = iStream.Read(buffer, 0, 10000);

                            // Write the data to the current output stream.
                            Response.OutputStream.Write(buffer, 0, length);

                            // Flush the data to the HTML output.
                            Response.Flush();

                            buffer = new Byte[10000];
                            dataToRead = dataToRead - length;
                        }
                        else
                        {
                            //prevent infinite loop if user disconnects
                            dataToRead = -1;
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Trap the error, if any.
                    Response.Write("Error : " + ex.Message);
                }
                finally
                {
                    if (iStream != null)
                    {
                        //Close the file.
                        iStream.Close();
                    }
                    Response.Close();
                }

What have I forgotten?

krisal
  • 621
  • 6
  • 19
  • What is the code you have for opening the file? That appears to be writing to a file, not opening one. – Andrew Backes May 03 '13 at 15:48
  • Do you want to know how to make your browser include an option to open the file directly in addition to saving it? – Jason May 03 '13 at 15:53
  • You're writing the file, you can only open it after it's been written to the file system. If it's a file type that can be read by a browser you could then redirect to it so it opens automatically? – Full Time Skeleton May 03 '13 at 16:26
  • How big your file will transfer from server to client? – Toan Vo May 03 '13 at 16:29
  • Is your button is in update panel.? if then you have to write postback trigger to download a file. – Kevin Shah May 03 '13 at 16:37
  • Have you tried a call to Response.Flush before Response.End? – Tim May 03 '13 at 16:39
  • BTW, your code quite messy, you should separate to small functions this will be help you easy to read, maintain. For example, you can separate it two functions one is GenerateDocument and another one is SendFileToClient. – Toan Vo May 04 '13 at 18:02
  • You should move the myDoc = null; and wordApp = null; after line System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp); – Toan Vo May 04 '13 at 18:31
  • Yeah but then they are not used anywere resharper tells me they get gray and when i have them after also i get same error when opening – krisal May 04 '13 at 18:34
  • by the way do u now why i get this warning , Warning 1 Ambiguity between method 'Microsoft.Office.Interop.Word._Application.Quit(ref object, ref object, ref object)' and non-method 'Microsoft.Office.Interop.Word.ApplicationEvents4_Event.Quit'. Using method group. C:\Users\Administrator\Documents\Visual Studio 2010\Projects\Cv.Knowit\Cv.Knowit\GenerateCv\GenerateCvUserControl.ascx.cs 2660 33 Cv.Knowit – krisal May 04 '13 at 18:47
  • @FullTimeSkeleton how could i redirect so it opens automacly? – krisal May 05 '13 at 16:00

1 Answers1

0

I will remove the line Response.AddHeader("Content-Length", file.Length.ToString());

Please follow rfc2616:

The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

Hope this help.

EDIT:

By the way, you should make sure the filePath variable which using at here already apply Server.MapPath and the file.Name should not contains the white space.

EDIT2:

Base on your comment, actually Response.WriteFile is not a good solution it work slowly and has many problem with large file you can take reference at here . You should apply response stream follow the link below by read file by stream and put it into memory and send back to client as the link below:

How do I put a WebResponse into a memory stream?

or

http://forums.asp.net/t/1794834.aspx/1

EDIT 3:

Your code posted here still not release Ms Word correctly, it still keeping your document so that's reason why you got exception as your comments.

Please follow the link below to resolve your problem.

Disposing of Microsoft.Office.Interop.Word.Application

Or

http://code.msdn.microsoft.com/office/CSAutomateWord-f422cae5

Community
  • 1
  • 1
Toan Vo
  • 1,270
  • 9
  • 19
  • alright so what should i use instead of content-length the page u showed me is really big i dont really now which one i should use ? – krisal May 04 '13 at 15:40
  • I have applied your code which it follow from my link posted here I can see it working as expected. I just create a button and put your code into button_Click event (asp.net Web form) the browser appears a dialog request open with or save as. If client have not default application to open .doc or .docx extension it will only require client save as. – Toan Vo May 04 '13 at 17:43
  • I have also done it on a button but when trying to open i get this Error, Word experienced an error trying to opet the file. Try these sugesstions. *Check the file permissions for the document or drive *Make sure there is suffient free memory and disk space. *Open the file with the text recovery convert – krisal May 04 '13 at 17:45
  • Oh, your problem totally another story. You should post another question. At my side, I can open it correctly. – Toan Vo May 04 '13 at 17:47
  • myDoc.Close(ref doNotSaveChanges, ref missing, ref missing); but does not this code close the document? i dont really now which part i should use on the page u send me... – krisal May 04 '13 at 18:06
  • The part you should apply at here is wordApp.Quit and System.Runtime.InteropServices.Marshal.ReleaseComObject(myDoc); and System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp); set them is null and call GC.Collect – Toan Vo May 04 '13 at 18:08
  • i get still same error using this code finally { myDoc.Save(); wordApp.Quit(ref doNotSaveChanges,ref missing,ref missing); if(myDoc!=null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(myDoc); } if(wordApp!=null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp); } GC.Collect(); – krisal May 04 '13 at 18:22
  • How about my comments 'set them is null'?. You should open Task Manager and cancel MS Word process which be launched by previous your mistakes and it still stay hidden in your computer . – Toan Vo May 04 '13 at 18:23
  • Object reference not set to an instance of an object. Ms Word is not running in my process cannot find it , so i should not me running in the process.. – krisal May 04 '13 at 18:27