Cmdlet file dialog implementation

ptxof8fRUH 1 Reputation point
2022-10-05T21:34:21.217+00:00

I have a console application in .NET 6 that hosts Powershell cmdlets using System.Management.Automation. I'm trying to make the cmdlet open up a file dialog inside the ProcessRecord method of the PSCmdlet but I haven't found a way to do this after an extensive search. I tried OpenFileDialog which comes from Windows Forms but it only works in the host. I would like it to be launched from within the cmdlet class. But calling ShowDialog throws this exception`ThreadStateException:

'Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThhreadAttribute marked on it. This exception is only raised if a debugger is attached to the process'`

and I do have the STAThread attribute on the host's Main.

So I would like to ask how exactly you go about implementing this.

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,462 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Limitless Technology 39,511 Reputation points
    2022-10-10T07:10:42.91+00:00

    Hi

    Thank you for posting your query.

    Kindly follow the steps provided below to resolve your issue.

    You want the OpenFileDialog https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.openfiledialog?redirectedfrom=MSDN&view=windowsdesktop-6.0 class

    This class allows you to check whether a file exists and to open it

    Do not hesitate to message us if you need further assistance.

    ----------------------------------------------------------------------------------------------------------------------------------------------------

    If the answer is helpful kindly click "Accept as Answer" and upvote it. Thanks.

    0 comments No comments