Kuczi
Kuczi

Reputation: 387

Console.ReadLine() without pressing Enter

When i use:

string fileName = Console.ReadLine();

The user has to drop the item and then press Enter. I want the user of my Console Application to be able to drag and drop a file into the Console Application Window and take the name of that file without him having to press Enter every time he drops the item as he has to drop a bunch of items.

The files extensions are .xlsx and .py. Is there a way of telling ReadLine to stop reading when it encounters these substrings?

Upvotes: 0

Views: 1789

Answers (3)

layonez
layonez

Reputation: 1785

As i know there is no really good solution for that case except making your own GUI. C# console cannot receive events from file drop, because csrss.exe owns that window not your app.

Next solution will not work in many cases, but if that just feature for testing not production i think that's enough.

    static void Main(string[] args)
    {
        StringBuilder fileNameBuilder = new StringBuilder();
        ConsoleKeyInfo cki = new ConsoleKeyInfo();

        do
        {
            while (Console.KeyAvailable == false)
                Thread.Sleep(250); 
            cki = Console.ReadKey(true);
            fileNameBuilder.Append(cki.KeyChar);
        } while (!fileNameBuilder.ToString().EndsWith(".xlsx") || !fileNameBuilder.ToString().EndsWith(".py"));

        var fileName = fileNameBuilder.ToString();
    }

Upvotes: 1

Martheen
Martheen

Reputation: 5580

Loop with Console.ReadKey(), extract the returned characters.

var filename = "";
do
{
    filename+= Console.ReadKey().KeyChar;

} while (!(filename.StartsWith("\"") && filename.EndsWith(".xlsx\"")) 
       && filename.EndsWith(".xlsx")); //continue with other extension

Notice the closing double quote, since you'll get quotes enclosing the filename if there's any space. This will break if there's .xlsx in the middle of the file name.

Upvotes: 2

ProTheJoker
ProTheJoker

Reputation: 45

The only way I know to do this, is by dragging files on the .exe file of your program, then reading their names from args[] (passed to main) and load them like you would with any file in C#.

Other way is by having a GUI, in that case you can add DragEventHandler objects to handle drag & drop events. (and data, too).

Upvotes: 1

Related Questions