如何将表单添加到控制台应用程序以便用户可以选择文件?
我已经创建了一个控制台应用程序,并按照我想要的方式工作。 使用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; }
我的静态主事件的那部分我希望从program.cs文件中创建“docPath”
static void Main(string[] args) { var excel = new ExcelQueryFactory(); excel.FileName = @"C:\Users\Christopher\Desktop\BookData\TestResults.xls"; }
感谢您的时间。
这是我完成的解决方案:
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(); } }
- 右键单击您的控制台应用程序,添加引用,
System.Windows.Forms
。 -
using System.Windows.Forms;
添加using System.Windows.Forms;
到你的文件的开头。 - 将
[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. } } }