如何将表单添加到控制台应用程序以便用户可以选择文件?

Chr*_*ris 4 c# openfiledialog console-application winforms

我创建了一个控制台应用程序,让它以我想要的方式工作.使用VS2010中的"添加项目">"添加Windows窗体"选项,它自动创建了我需要的内容.我添加了一个按钮和代码来检索Excel文件(如下所示)我的问题是:

如何获取他们创建的文件并在program.cs"Main"区域中使用它?

来自Form1.cs的OpenFileDialog按钮单击事件的代码:

private void btnSelect_Click(object sender, EventArgs e)
{
OFD.openFileDialog OFD = new OpenFileDialog();
OFD.Multiselect = false;
OFD.Title = "Open Excel Document";
OFD.Filter = "Excel Document|*.xlsx;*.xls";
OFD.ShowDialog();
string docPath = OFD.FileName;
}
Run Code Online (Sandbox Code Playgroud)

我的静态主事件的那部分我希望从program.cs文件中创建"docPath"

static void Main(string[] args)
    {
        var excel = new ExcelQueryFactory();
        excel.FileName = @"C:\Users\Christopher\Desktop\BookData\TestResults.xls";
       <...code executed on opened excel file...>
     }
Run Code Online (Sandbox Code Playgroud)

感谢您的时间.

这是我完成的解决方案:

class Program
{
    [STAThread]
    static void Main(string[] args)
    {

        var excel = new ExcelQueryFactory();
        OpenFileDialog OFD = new OpenFileDialog();
        OFD.Multiselect = false;
        OFD.Title = "Open Excel Document";
        OFD.Filter = "Excel Document|*.xlsx;*.xls";
        OFD.ShowDialog();
        string filePath = OFD.FileName;
        excel.FileName= filePath.ToString();
        <.the rest of my program is below...>
    }  
}
Run Code Online (Sandbox Code Playgroud)

Ada*_*dam 12

  1. 右键单击您的控制台应用程序,添加引用,System.Windows.Forms.
  2. 添加using System.Windows.Forms;到文件的开头.
  3. [STAThread]属性添加到您的属性以Main使其与打开的文件对话框兼容.

[STAThread]
public static void Main(string[] args)
{
    var dialog = new OpenFileDialog
                     {
                         Multiselect = false,
                         Title = "Open Excel Document",
                         Filter = "Excel Document|*.xlsx;*.xls"
                     };
    using (dialog)
    {
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            var excel = new ExcelQueryFactory { FileName = dialog.FileName };
            // code executed on opened excel file goes here.
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是不合法的,STA线程*必须*泵送消息循环.不这样做的副作用是死锁和不会触发的事件.特别是使用COM对象时的问题.OP正试图怀孕一点. (3认同)
  • @HansPassant 很有趣。我不知道这一点,很乐意提出更好的解决方案。 (2认同)