在 Word 文档处于活动状态时将其转换为二进制文件

Convert the Word Document to Binary while it is active

我需要将word文档保存到数据库中。这样做的问题是,我的文档处于活动状态,因此创建的加载项无法访问它。 这是我的代码,需要访问活动文档!

var doc = Globals.ThisAddIn.Application.ActiveDocument;
//string FilePath = "C:/Users/karthikeyan.g/Downloads/Top10thingsToCreateFunctions.docx";
string OrgPath = doc.Path;
string FilePath = OrgPath.Replace('\', '/') + '/' + doc.Name;
//string FilePath = Path.GetTempFileName(); 
      try
        {
            FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);
            Byte[] bytes = br.ReadBytes((Int32)fs.Length);
            string strQuery = "insert into wordFiles(Name,ContentType,Data) values(@Name,@ContentType,@Data)";
            SqlCommand cmd = new SqlCommand(strQuery);
            cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = doc.Name;
            cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = "docx";
            cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
            br.Close();
            fs.Close();

            if (InsertUpdateData(cmd))
            {
                MessageBox.Show("Inserted!");
            }
            else
            {
                MessageBox.Show("Not Inserted!");
            }
        }

可能重复: Serialize current ActiveDocument from office 2007 add-in

来自MSDN博客的回答:使用IPersistFile接口。 http://blogs.msdn.com/b/pranavwagh/archive/2008/04/03/how-to-do-a-save-copy-as-in-word.aspx

using System.Runtime.InteropServices.ComTypes;

var pf = (IPersistFile) Globals.ThisAddIn.Application.ActiveDocument;
pf.Save(@"C:\Temp\hello.doc", false);