Search code examples
c#.net-corems-wordoffice-interopasp.net-core-8

How to automate Office Word from a .Net 8 C# Console application


I am trying to automate Office Word from a .Net 8 Console application.

This is my code:

internal class Program
{
    static void Main(string[] args)
    {            
        var appWord = new Microsoft.Office.Interop.Word.Application();

        Console.WriteLine("Hello, World!");
    }
}

This is how my .csproj file looks like:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <Reference Include="Microsoft.Office.Interop.Word">
      <HintPath>C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Word\15.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Word.dll</HintPath>
    </Reference>   
  </ItemGroup>

</Project>

When I try to run my application in Debug mode from inside VS I get the following error:

System.IO.FileNotFoundException: 'Could not load file or assembly 'office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'. The system cannot find the file specified.'

I cannot understand why I get this error. I have explicitly added the file using a COM Reference, as can be seen from the .csproj file. Any help would be greatly appreciated!


Solution

  • When I browse for word in the references (as You apparently are doing), I get the same content in the project file.

    BUT if I locate word using the COM reference I get another content in ItemGroup:

      <ItemGroup>
        <COMReference Include="Microsoft.Office.Interop.Word">
          <WrapperTool>tlbimp</WrapperTool>
          <VersionMinor>7</VersionMinor>
          <VersionMajor>8</VersionMajor>
          <Guid>00020905-0000-0000-c000-000000000046</Guid>
          <Lcid>0</Lcid>
          <Isolated>false</Isolated>
          <EmbedInteropTypes>true</EmbedInteropTypes>
        </COMReference>
      </ItemGroup>
    

    THIS runs without errors on my computer (the other version does return the same error as yours).

    This is how my COMreference selector looks:

    enter image description here

    By the way: remember that the code actually starts a (hidden) version of Word!