Thursday, March 2, 2023

Fixing "The type or namespace 'Windows' could not be found" error CS0246

"The type or namespace 'Windows' could not be found" solution!

Every time I install a new version of Visual Studio, I run into just a metric hand-full of errors from previously working projects. The projects haven't changed, but suddenly Visual Studio is seemingly incapable of finding the "Windows" namespace.

My Solution: run the Visual Studio Installer". Pick your installed version and click Modify. The modification you probably want is to under Universal Windows Platform development in the Optional section. Look at the list of available Windows SDK and just install them all (assuming you have enough disk space).

There's no harm (AFAICT) in getting them all, and it will save you heartache and frustration down the line.

This entire process is just a cluster. What's more common than building apps for Windows using the compiler tools from Microsoft that are specifically designed to build Windows apps? Well, the only thing more common then developing windows apps is seeing yet another place where Visual Studio once again makes development more painful.

For me, the #1 reason I get the error is that I don't have enough of the Windows SDKs installed. By default, the Visual Studio installer only installs the "most recent" SDK. You might think that's enough, but it's not.

Each project will have a reference path that looks like this:

    <Reference Include="Windows.Foundation.UniversalApiContract">
      <HintPath>..\..\..\..\..\..\Program Files (x86)\Windows Kits\10\References\10.0.22010.0\Windows.Foundation.UniversalApiContract\14.0.0.0\Windows.Foundation.UniversalApiContract.winmd</HintPath>
    </Reference>

Note how the HintPath specifies exactly one particular SDK. If you have a more recent version, it doesn't count even though the contracts are specifically designed to be upwards compatible.

What's worse, Visual Studio loves to kind of silently update your project files, so you'll silently be updated, potentially breaking the project on a different computer.

Error CS0246 The type or namespace name 'Windows' could not be found (are you missing a using directive or an assembly reference?)

No comments: