Post

.NET Methods Don't Expand Paths

Relative paths are interpreted differently in .NET methods than in PowerShell.

Problem

I encountered an error when working with the .NET namespace System.Security.Cryptography.X509Certificates. Despite being in the directory where the certificate file was located, the system could not find the file and threw an exception.

relative-path-exception

While PowerShell automatically resolves relative paths based on the current directory, .NET methods do not. In .NET, when you provide a relative path, it is interpreted relative to the current working directory of the application process, not necessarily the location of the script/executable.

Resolution

I resolved it by calling the class using the expanded full path of the certificate.

1
[Security.Cryptography.X509Certificates.X509Certificate2]::New([System.IO.Path]::GetFullPath((Join-Path (Get-Location) $Certificate)))

expanded-path

By using System.IO.Path.GetFullPath, I was able to provide the full path of the certificate file to the .NET method, which successfully loaded the certificate.

References

This post is licensed under CC BY 4.0 by the author.