Search code examples
c#consolewindows-forms-designer

is it possible to create an attachment box to fetch FilePath using C# console as in Windows Form?


so I have this code that fetches me lines and columns from an ExcelPath(path/to/excel/file.xlsx) and shows it in the Console, but going forward I will make other uses of the lines and columns imported from excel. I would like to instead of including the ExcelPath using the Console.ReadLine() use it as the OpenFileDialog of the Windows Form would it be possible to do something similar in the console?

public void ImportExcel()
    {
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

        Console.WriteLine("Insert path to excel file");
        Console.WriteLine("ex : path/to/excel/file.xlsx");

        string excelPath = Console.ReadLine();
        using var stream = File.Open(excelPath, FileMode.Open, FileAccess.Read);
        using var reader = ExcelReaderFactory.CreateReader(stream);

        if (reader.Name != null)
        {
            Console.WriteLine($"Loading sheet name: {reader.Name}");
        }

        while (reader.Read())
        {
            for (int i = 0; i < reader.FieldCount; i++)
            {
                Console.Write(reader.GetValue(i) + "\t");
            }
            Console.WriteLine();
        }

Solution

  • Add reference

    System.Windows.Forms;
    System.Drawing.Common;
    

    Full sample code for .NET Core 3.1

    using System;
    using System.Windows.Forms;
    
    namespace OpenFileDialogTest
    {
        internal class Program
        {
            [STAThread]
            static void Main(string[] args)
            {
    
                // Create an instance of the OpenFileDialog class
                OpenFileDialog openFileDialog = new OpenFileDialog();
    
                // Set the initial directory and filter for the file dialog
                openFileDialog.InitialDirectory = "C:\\";
                openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
    
                // Show the dialog and get the result
                DialogResult result = openFileDialog.ShowDialog();
    
                // If the user clicked OK, get the selected file path and read the file
                if (result == DialogResult.OK)
                {
                    string filePath = openFileDialog.FileName;
                    Console.WriteLine($"Selected file: {filePath}");
    
                    // Read the contents of the file
                    string fileContents = File.ReadAllText(filePath);
                    Console.WriteLine("File contents:");
                    Console.WriteLine(fileContents);
                }
                else
                {
                    Console.WriteLine("No file selected.");
                }
    
                Console.ReadLine();
            }
        }
    }
    

    Full sample code for .NET 6 top level statement

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    // Use a helper method to run the OpenFileDialog in a separate STA thread
    string selectedFilePath = await RunStaThread(() =>
    {
        // Create a new instance of the OpenFileDialog class
        using OpenFileDialog openFileDialog = new OpenFileDialog
        {
            // Set the initial directory and filter for the file dialog
            InitialDirectory = "C:\\",
            Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"
        };
    
        // Show the dialog and get the result
        return openFileDialog.ShowDialog() == DialogResult.OK
            ? openFileDialog.FileName // If the user clicked OK, return the selected file path
            : null; // Otherwise, return null
    });
    
    // Check if a file was selected and display its contents
    if (selectedFilePath != null)
    {
        Console.WriteLine($"Selected file: {selectedFilePath}");
    
        // Read the contents of the file
        string fileContents = File.ReadAllText(selectedFilePath);
        Console.WriteLine("File contents:");
        Console.WriteLine(fileContents);
    }
    else
    {
        Console.WriteLine("No file selected.");
    }
    
    // Wait for user input before exiting the console application
    Console.ReadLine();
    
    // Helper method to run code in a separate STA thread
    static async Task<T> RunStaThread<T>(Func<T> func)
    {
        // Create a new TaskCompletionSource object to await the result of the STA thread
        TaskCompletionSource<T> taskCompletionSource = new TaskCompletionSource<T>();
    
        // Create a new thread and set its apartment state to STA
        Thread thread = new Thread(() =>
        {
            try
            {
                // Run the provided code on the STA thread and set the result of the TaskCompletionSource object
                taskCompletionSource.SetResult(func());
            }
            catch (Exception ex)
            {
                // If an exception is thrown, set the exception on the TaskCompletionSource object
                taskCompletionSource.SetException(ex);
            }
        });
    
        // Set the apartment state of the new thread to STA
        thread.SetApartmentState(ApartmentState.STA);
    
        // Start the new thread
        thread.Start();
    
        // Await the result of the STA thread and return it
        return await taskCompletionSource.Task;
    }