简体   繁体   中英

How to programmatically submit a password to a stand alone program in C#

I am making a C# application (using Microsoft Visual Studio 2015, using WinForms) that needs to open a password protected .docx file in C#. I know you can do:

Process.Start("WINWORD.EXE", "filename.docx");

To start word (I'm using Microsoft Word 2016) with that file loaded in. But I also want to submit the password to Word so it opens without me doing anything. I know it's not this simple, but this is what imagining right now:

public void submitPassword(string password)
{
    Process.Start("WINWORD.EXE", "filename.docx" //something like this: System.Password.Sumbit("WINWORD.EXE", password));
}

There is a COM type library called Microsoft Word Object Library . In Visual Studio, you can add a reference to it from the solution explorer. Right click References, click Add Reference, go to the COM tab, and search for Word.

With the package Microsoft.Office.Interop.Word , you can create an Application instance and tell it to open a document using a password.

using Microsoft.Office.Interop.Word;

...

public void SubmitPassword(string password)
{
    Application app = new Application();
    app.Documents.Open(FileName: @"filepath", PasswordDocument: password);
}

The answer provided to me by Andrew Piliser got me close, but not there. This is what works:

   using Word = Microsoft.Office.Interop.Word;
   ...
   public void submitPassword()
   {
        var wordApp = new Word.Application();
        wordApp.Visible = true;
        wordApp.Documents.Open(FileName: @"filepath", PasswordDocument: "filepassword");
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM