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
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.
}
}
}
Run Code Online (Sandbox Code Playgroud)