How to add a form to the console application so that the user can select a file?

I created a console application and work the way I want. Using the option Add Item> Add Windows Form to VS2010, it automatically created what I needed. I added a button and code to extract the Excel file (below). My question is:

How to take the file they created and use it in my main program.cs program area?

Code for the OpenFileDialog button click event, from 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; } 

This is the part of my static main event that I want to do "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 complete 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...> } } 
+4
source share
1 answer
  • Right-click your console application, add the link, System.Windows.Forms .
  • Add using System.Windows.Forms; to the top of your file.
  • Add the [STAThread] attribute to your Main so that it is 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. } } } 
+12
source

Source: https://habr.com/ru/post/1435775/


All Articles