Is there a way to import PST files into Outlook using C#?

走远了吗. 提交于 2019-12-11 03:36:38

问题


Using: Visual Studio 2017 (Language: C#)

I have a similar function written below in PowerShell script, but I need the C# version of it to execute on the click of a button within Visual Studio:

Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
$outlook = new-object -comobject outlook.application

$namespace = $outlook.GetNameSpace("MAPI")

dir “$env:userprofile\Documents\Outlook Files\*.pst” | % { $namespace.AddStore($_.FullName) }

Any insight or examples of code would be much appreciated.


回答1:


You can do that the following way:

In your project, right click on "References" and add a reference to the assembly "Microsoft.Office.Interop.Outlook".

Then you can use the following code:

/// <summary>
/// Get a reference to an already running or a newly started Outlook instance
/// </summary>
Microsoft.Office.Interop.Outlook.Application GetOutlookApp()
{
    Microsoft.Office.Interop.Outlook.Application app = null;

    // Try to get running instance
    try
    {
        app = Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application;
    }
    catch(Exception)
    {
        // Ignore exception when Outlook is not running
    }

    // When outlook was not running, try to start it
    if(app == null)
    {
        app = new Microsoft.Office.Interop.Outlook.Application();
    }

    return app;
}

private void button1_Click(object sender, EventArgs e)
{
    const string fileName = @"D:\MyDings.pst";

    var app = GetOutlookApp();
    var nameSpace = app.GetNamespace("MAPI");

    nameSpace.AddStore(fileName);

    MessageBox.Show("Done");
}



回答2:


I'm not 100% sure if it is possible without extra packages. So I would just do a shell command executing the powershell script, since you already have that. Bit of a hack but seems the easiest option.

using System.Diagnostics;
Process.Start("powershell.exe " + scriptLocation);


来源:https://stackoverflow.com/questions/49559535/is-there-a-way-to-import-pst-files-into-outlook-using-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!