Search code examples
c#wpftextboxlistboxstreamreader

Loading Text from a file into a Text box


I am trying to load a text file into a textbox. The file that is to be loaded is selected from a Listbox UnViewed_Messages however when I try and load the file it does nothing.

The code used to populate the list box is below:

public Quarantine_Messages()
    {
        InitializeComponent();
        //loads in files to the list box on load
        DirectoryInfo DirFiles = new DirectoryInfo(@"C:\User\***\Documents\Noogle system\Quarantin_Messages");
        FileInfo[] Files = DirFiles.GetFiles("*.txt");
        foreach (FileInfo file in Files)
        {
            UnViewed_Messages.Items.Add(file.Name);
        }
    }

This is the code I am using to try and load the text file into the textbox Message_Viewer

 private void Open_Message_Content_Click(object sender, RoutedEventArgs e)
    {
        //tries to read in the file to the text box Message_Viewer
        string[] Files = Directory.GetFiles(@"C:\User\***\Documents\Noogle system\Quarantin_Messages");
        foreach (string file in Files)
        {
            if (System.IO.Path.GetFileName(file) != UnViewed_Messages.SelectedItems.ToString())
            {
                using (var viewer = new StreamReader(File.OpenRead(file)))
                {
                    Message_Viewer.Text = viewer.ReadToEnd();
                    viewer.Dispose();
                }
            }
        }
    }

Any help with this would be greatly appreciated, Thanks in advance.


Solution

  • Try something like this maybe:

        private FileInfo[] files;
        private DirectoryInfo directory;
    
        private void Form1_Load(object sender, EventArgs e)
        {
            directory = new DirectoryInfo(@"C:\Users\smelendez\downloads");
            files = directory.GetFiles("*.txt");
            foreach (FileInfo file in files)
            {
                listBox1.Items.Add(file.Name);
            }
        }
    
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var selectedFile = files[listBox1.SelectedIndex];
    
            richTextBox1.Text = "";
            richTextBox1.Text = File.ReadAllText(selectedFile.FullName);
        }
    

    And then continue from there with whatever logic you need.