How to do a "Save Copy As" In Word

Ever wondered how can you do a "Save Copy As" in word? Or why it's not there?  well ... I don't know about why it's not there, but I can tell you how to do it using custom code

To do it, the first thing you need to know about is - IPersistFile interface, this interface provides methods that permit an object to be loaded from or saved to a disk file, rather than a storage object or stream. As this is one of the compound document interfaces, word implements it.

Getting back to the theory, whenever any component implements an interface it has to implement all of it's methods, which in turn gets added to  the vtable of the component, whenever you want to use this interface from an external client you need to obtain a it's pointer,  then you can call any of the methods from this interface.

Here is a sample code in C#. Yes! it's a simple code, the only reason is System.Runtime.InteropServices.ComTypes Namespace which contains methods that are defintions of COM functions for managed code including IPersistFile.

If this was not available, then I might have been required to play a lot of "Marshal." and/or Win32API games to get this thingy working  -

 

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
using System.Reflection;
using System.Runtime.InteropServices;
using COM = System.Runtime.InteropServices.ComTypes;

namespace IPersistFileFromWord
{
    public partial class Form1 : Form
    {

        Word.Application wdApp;
        Word._Document wdDoc;
        object o=Missing.Value;
        public Form1()
        {
             InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            wdApp= new Word.Application();
            wdDoc=wdApp.Documents.Add(ref o,ref o, ref o, ref o);
            wdDoc.Range(ref o, ref o).Text = "Hello World ...";
            wdApp.Visible = true;
            COM.IPersistFile pp = (COM.IPersistFile)wdDoc;
            pp.Save(@"C:\upload\Something.doc",false);
        }
    }
}

Enjoy and take care ...

 

del.icio.us tags: Pranav+Wagh, Microsoft+Blogger, Word, C#, HowTo

Technorati tags: Pranav+Wagh, Microsoft+Blogger, Word, C#, HowTo