Mateusz
Mateusz

Reputation: 2317

C# console application command session history

I have simple command line application, and I want to store commands typed in between starts of program.

Storing alone is not problem, I know how to do it, but how I can restore it? Console class don't have any method for setting history, if I press up arrow on start of application it is empty.

Methods from msdn for unmanaged code are not helpful for me, good answer could show me how to use them in c# to get what I need.

My idea is to override up arrow with ReadKey only and do it "hard" way but if there is easier way I would be glad.

Upvotes: 2

Views: 2272

Answers (3)

Mateusz
Mateusz

Reputation: 2317

In case someone looks for something like it, I ended up using powershell and set of scripts, but I managed to setup powershell history:

https://software.intel.com/en-us/blogs/2014/06/17/giving-powershell-a-persistent-history-of-commands

$HistoryFilePath = Join-Path ([Environment]::GetFolderPath('UserProfile')) .ps_history
Register-EngineEvent PowerShell.Exiting -Action { Get-History | Export-Clixml $HistoryFilePath } | out-null
if (Test-path $HistoryFilePath) { Import-Clixml $HistoryFilePath | Add-History }
# if you don't already have this configured...
Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward

Save that code to file: C:\Users\\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

Upvotes: 0

sorrell
sorrell

Reputation: 1871

I know this is an old question, but I was searching for an answer too. Couldn't find one though, so I built InteractivePrompt. It's available as a NuGet Package and you can easily extend the code which is on GitHub. It features a history for the current session, but I plan to implement functionality to save the commands between sessions.

It's a very useful package for wrapping DLLs, like SQLite for instance.

Upvotes: 1

Andre Lombaard
Andre Lombaard

Reputation: 7105

I would simply save the commands as XML or in a relational database, when needed I will deserialize the XML to the appropriate objects stored as a list or possibly an array (if you have a defined number of commands, for instance the last 10). Then override the appropriate event as you mentioned and iterate the list of command objects by keeping a counter of where you are in the list.

Upvotes: 1

Related Questions