在活动时将Word文档转换为二进制文件

时间:2015-03-18 10:44:50

标签: c# ms-word add-in

我需要将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!");
            }
        }

1 个答案:

答案 0 :(得分:0)

可能是以下副本: 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);