简体   繁体   中英

How can I make a live loading richbox from my txtfile?

i made a form with a textbox and a richbox.... The thextbox is : Command editor and the Richbox is : Command history All my commands that i entered in command editor goes into "QueryCommands.txt". How can i make the Richbox to update automaticaly after i write a Command into a command editor.

private void WW_Shown(object sender, EventArgs e)
{
    string strfilename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "QueryCommands.txt");
    string commandstext = File.ReadAllText(strfilename);
    richTextBox2.Text = commandstext;
}

this is the Richbox loader... I need to Load everytime The Form to make an update.. And i want that the richbox loads the commands automaticaly the commands from my QueryCommands.txt

No. Don't load the form again. just provide the logic at the end of your button, which you use for entering command. something like:

private void commandBtn.Click(object sender, EventArgs e)
{
   //other logic


   //load text to richtextbox again (update richtextbox)
}

I suggest that on the button click, you perform two activities

  1. Append the command into the text file
  2. Append the command at the end of RichTextBox

If you load from the file everytime, that will cause a lot of I/O operations on the storage drive.

If you wish to show the history of commands during last session (before the program was closed); then load the command history from text file during Form_Load

I your events a separated and you want to inform your RichTextBox when for example the file was updated, you can use the FileSystemWatcher class in order to monitor the file for changes. Example code looks like this:

// monitor all *.dat files in the d:\temp directory
var fsw = new FileSystemWatcher("d:\\temp\\", "*.dat");
// only when they are changed
fsw.NotifyFilter = NotifyFilters.LastWrite;
// register to change event
fsw.Changed += OnChanged;

private static void OnChanged(object source, FileSystemEventArgs e)
{
    // for example reload file using File.ReadAllText(e.FullPath);
   Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
}

If everything is taking place in the same application, than consider implementing the approach suggested by @Manish Dalal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM