简体   繁体   中英

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

I am trying to code a program which is executed when a file is right clicked in windows, and then a context menu feature named 'Move to' executes a file in the windows registry HKEY ClASSES. It ought to parse in "%1" as argument when it executes, so that my program knows where the file is located. However, when I compile my single .cs file, the FolderBrowserDialog won't show. I am suspecting that it is because I haven't initialized some kind of form before I call it. Is it possible in some way to choose a folder from a single c# file without including 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());
            }
        }   
    }
}

If you bypass the argument check and try to show the FBD in a debugger, with this exact code, you will see 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.'

As per the error message, this exception won't be raised if no debugger is attached. Put an [STAThread] attribute on your Main method, like you normally see in any windows forms app:

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

I also recommend you add an else for your outer if, to show an error if no arguments are passed (otherwise your app will exit silently

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM