How do I add a form to a console app so that user can select file?

自闭症网瘾萝莉.ら 提交于 2020-01-23 01:11:07

问题


I have created a console application and have it working the way I want it to. Using the "Add Item" > "Add Windows Form" option in VS2010, it has automatically created what I need. I have added a button and code to retrieve an Excel file (below) My question is:

How do I take the file they have created and use it in my program.cs "Main" area?

The code for the OpenFileDialog button click event, from the Form1.cs:

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;
}

That part of my static main event I wish to make "docPath" from the program.cs file

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

Thank you for your time.

This is my completed solution:

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...>
    }  
}

回答1:


  1. Right click your Console application, add reference, System.Windows.Forms.
  2. Add using System.Windows.Forms; to the beginning of your file.
  3. Add the [STAThread] attribute to your Main to make it compatible with the open file dialog.

[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.
        }
    }
}


来源:https://stackoverflow.com/questions/12553932/how-do-i-add-a-form-to-a-console-app-so-that-user-can-select-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!