bdg
bdg

Reputation: 465

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.

Upvotes: 1

Views: 7787

Answers (2)

Mafii
Mafii

Reputation: 7455

Instead of your streamreader, just use:

string[] lines = File.ReadAllLines(file);
Message_Viewer.Text = String.Join(Environment.NewLine, lines)

Thats all. C#/.NET I/O is really clean if you know the stuff.

Edit: Keep in mind that with really big files, you would still have to use a filestream to read and add line by line, but it really shouldn't be a problem. I mean fill your ram with lines of text and then we talk again, okay?

MSDN File-I/O

Upvotes: 0

Steven Melendez
Steven Melendez

Reputation: 153

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.

Upvotes: 2

Related Questions