1

我通过使用合并字段为用户自定义模板,从模板生成 word 文档。例如: 名称:“用户名”。现在我使用将文档保存在服务器上

object miss = System.Reflection.Missing.Value;
            object oDocName = "C:\\Users\\admin\\Desktop\\test002.doc";
            wordDoc.SaveAs(ref oDocName, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
            ((_Application)wordApp).Quit(ref miss, ref miss, ref miss);

然后,我使文档可供下载:

protected void download_Click(object sender, EventArgs e)
{ 
    FileStream fileStream = new FileStream("C:\\Users\\ebimbari\\Desktop\\test002.doc", FileMode.Open);

    int fileSize = (int)fileStream.Length;
    byte[] Buffer = new byte[fileSize];

    fileStream.Read(Buffer, 0, fileSize);
    fileStream.Close();

    Response.ContentType = ContType("C:\\Users\\admin\\Desktop\\test002.doc");
    Response.BinaryWrite(Buffer);
    Response.AddHeader("content-disposition", "attachment;filename=\"" + "form" + ".doc");
    Response.End();
}

问题是我不希望将表单保存在服务器上。我可以直接打开使其可供下载的文档吗?我正在使用Microsoft.Office.Interop.Word

谢谢。

4

1 回答 1

2

使用魔法IsolatedStorageFile

编辑:“如何拥有文件的持久副本,而不将其实际保存到硬盘”的答案是 - 使用神奇的IsolatedStorageFile.

(“神奇”这个词可能会被省略)。

我无法测试这段代码,也不确定worddoc.SaveAs(...)行为如何。请测试并告诉我:

    private static readonly string CACHE =  @"MyWordCache";

    static void PutFile(object wordDoc, string fname)
    {
        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if (!store.DirectoryExists(CACHE))
                store.CreateDirectory(CACHE);

            object fullname = Path.Combine(CACHE, fname);
            wordDoc.SaveAs(ref fullname, ...);
        }
    }

    protected bool Downloadfile(string fname)
    { 
        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if (!store.DirectoryExists(CACHE))
                return false;

            var fullname = Path.Combine(CACHE, fname);
            using (var fileStream = store.OpenFile(fullname, FileMode.Open))
            {
                int fileSize = (int)fileStream.Length;
                byte[] Buffer = new byte[fileSize];

                fileStream.Read(Buffer, 0, fileSize);

                Response.ContentType = ContType(fullname);
                Response.BinaryWrite(Buffer);
                Response.AddHeader("content-disposition", "attachment;filename=\"" + "form" + ".doc");
                Response.End();
            }
        }
        return true;
    }
于 2012-11-10T10:23:35.097 回答