C# 下载文件

C# 下载文件,c#,asp.net,C#,Asp.net,现在我正在处理一个项目,我需要制作一个下载按钮。一切都很好,但我只能在我想下载文件时单击“保存”或“另存为”,当我单击“打开”时,什么都没有发生,为什么 string path = filePath.ToString(); FileInfo file = new FileInfo(path); if (file.Exists) { Response.Clear(); Response.AddHeader("Content-Disposition", "attachment; fi

现在我正在处理一个项目,我需要制作一个下载按钮。一切都很好,但我只能在我想下载文件时单击“保存”或“另存为”,当我单击“打开”时,什么都没有发生,为什么

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();
}
更新*不工作,仅打开保存

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

我忘记了什么?

我将删除行
Response.AddHeader(“Content-Length”,file.Length.ToString())

请注意:

Content-Length实体标题字段指示实体的大小 发送给收件人的实体体,以十进制八位字节数表示,或 在HEAD方法的情况下,实体体的大小 如果请求是GET,则已发送

希望这有帮助

编辑

顺便说一下,您应该确保此处使用的
filePath
变量已应用
Server.MapPath
,并且
file.Name
不应包含空格

EDIT2

根据您的评论,实际上
Response.WriteFile
并不是一个好的解决方案,它工作速度慢,并且对于您可以参考的大文件有很多问题。您应该应用响应流,通过逐个流读取文件并将其放入内存,然后按照下面的链接发送回客户端,如下所示:

编辑3:

你们在这里发布的代码仍然并没有正确地发布Ms Word,它仍然保留着你们的文档,所以这就是为什么你们的评论出现异常的原因

请按照下面的链接解决您的问题


打开文件的代码是什么?这似乎是在写入文件,而不是打开文件。是否希望知道如何使浏览器在保存文件的同时还包括一个直接打开文件的选项?在写入文件时,只能在将文件写入文件系统后才能打开该文件。如果它是一种可以被浏览器读取的文件类型,您可以重定向到它,使其自动打开?您的文件将从服务器传输到客户端的大小?按钮是否在“更新”面板中。?如果你需要写回发触发器来下载一个文件。好吧,那么我应该用什么来代替内容长度呢?你给我看的页面真的很大,我现在不知道该用哪一个?我已经应用了你的代码,从我在这里发布的链接中可以看到它按预期工作。我只需创建一个按钮并将代码放入按钮单击事件(asp.net Web表单)浏览器将显示一个对话框请求打开或另存为。如果客户端没有打开.doc或.docx扩展名的默认应用程序,则只需要客户端另存为。我也在按钮上执行了此操作,但在尝试打开时出现此错误,Word在尝试操作文件时遇到错误。试试这些建议*检查文档或驱动器的文件权限*确保有足够的可用内存和磁盘空间*用文本恢复转换器打开文件哦,你的问题完全是另一回事了。你应该发布另一个问题。在我这边,我可以正确地打开它。myDoc.Close(ref-doNotSaveChanges、ref-missing、ref-missing);但是这段代码不关闭文档吗?我现在真的不知道我应该在你给我的页面上使用哪一部分。。。