FolderBrowserDialog 不会显示在没有 Form 的单个 .cs 文件中

FolderBrowserDialog won't show in a single .cs file without Form

我正在尝试编写一个程序,该程序在 windows 中右键单击文件时执行,然后名为 'Move to' 的上下文菜单功能在 windows 中执行文件注册表 HKEY 类。它应该在执行时将“%1”解析为参数,以便我的程序知道文件所在的位置。但是,当我编译单个 .cs 文件时,FolderBrowserDialog 不会显示。我怀疑这是因为我在调用它之前没有初始化某种形式。是否可以通过某种方式从单个 c# 文件中选择一个文件夹而不包括 Forms?

using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;


public class MoveTo : Form 
{

    public static string current_file_path;
    public static string new_file_path;
    public static string file_name;

    public static void Main(string[] args){
        if (args.Length > 0)
        {
            current_file_path = (string) args[0];
            file_name = (string) current_file_path.Replace(Path.GetDirectoryName(Environment.GetCommandLineArgs()[1]), "");
            var browser = new FolderBrowserDialog();

            if (browser.ShowDialog()==DialogResult.OK)
            {
                new_file_path = browser.SelectedPath + file_name;
            }else
            {
                Environment.Exit(1);
            }
            try
            {
                File.Move(current_file_path, new_file_path);    
            }catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }   
    }
}

如果您绕过参数检查并尝试在调试器中显示 FBD,使用这个确切的代码,您将看到 System.Threading.ThreadStateException:'Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process.'

根据错误消息,如果没有附加调试器,则不会引发此异常。在你的 Main 方法上放置一个 [STAThread] 属性,就像你通常在任何 windows 表单中看到的那样 app:

[STAThread]
public static void Main(string[] args)
{ 
  ...

我还建议您为外部 if 添加一个 else,以在未传递任何参数时显示错误(否则您的应用将静默退出