如何将表单添加到控制台应用程序,以便用户可以选择文件? [英] How do I add a form to a console app so that user can select file?
问题描述
我已经创建了一个控制台应用程序,并使它按照我想要的方式工作.使用VS2010中的添加项目">添加Windows窗体"选项,它会自动创建我需要的内容.我添加了一个按钮和代码来检索Excel文件(如下),我的问题是:
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:
如何获取他们创建的文件并在我的program.cs主要"区域中使用它?
How do I take the file they have created and use it in my program.cs "Main" area?
OpenFileDialog按钮单击事件的代码,来自Form1.cs:
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;
}
我希望从program.cs文件中创建"docPath"作为静态主要事件的一部分
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...>
}
谢谢您的时间.
这是我完成的解决方案:
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...>
}
}
推荐答案
- 右键单击您的控制台应用程序,添加引用
System.Windows.Forms
. - 在文件的开头添加
using System.Windows.Forms;
. - 在您的
Main
中添加[STAThread]
属性,使其与打开的文件对话框兼容.
- Right click your Console application, add reference,
System.Windows.Forms
. - Add
using System.Windows.Forms;
to the beginning of your file. - Add the
[STAThread]
attribute to yourMain
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.
}
}
}
这篇关于如何将表单添加到控制台应用程序,以便用户可以选择文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!