Skip to content

Opening files and listboxes

Drew Taylor

Asked Jun 7, 2007, 4:45 AM EDT10 answers
Share
LinkedInX

I want to be able to browse files using a listbox and another list box which displays the contents of the file selected in the first listbox when the user clicks a button.

Can someone show me how to do this?

10 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    Let me get this into focus here, you want a listbox to display the names of all the files that are in a certain directory, and then have another listbox display the contents of the selected file from the first listbox when the user clicks a button, correct?
    Couldnt you have the user select a file name from the listbox, then have the contents displayed in a rich text box when the user clicks a button? Just a thought that would be a bit easier to work with :)

    -Scrap
    0
  • 0

    That sounds good how would I do that?

    But I want to be able to select a folder in a listbox (first) which will then display files within that folder in another list box and when these files are selected the contents will be displayed in a rich text window (they will all be text files)

    How can I do this?

    0
  • 0
    Here, this isnt EXACTLY what your looking for (its minus the folders list) but I think it should really help you out:

    C#
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    
    namespace ExamplesApp
    {
    public partial class MainForm : Form
    {
    //Declare the file path, it can be anything you want it to be
    internal string filePath = ("C:/Documents and Settings/a/My Documents/txt files/");
    public MainForm()
    {
    InitializeComponent();
    }
    private void startButton_Click(object sender, EventArgs e)
    {
    //-------------------
    //-startButton_Click-
    //-------------------
    //Get all files listed in specified directory
    DirectoryInfo dInfo = new DirectoryInfo(filePath);
    FileInfo[] fInfo = dInfo.GetFiles("*.txt");
    //For each file found, display the name in a list box
    foreach (FileInfo FI in fInfo)
    {
    filesListBox.Items.Add(FI);
    }
    }
    private void filesListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
    //-----------------------------------
    //-filesListBox_SelectedIndexChanged-
    //-----------------------------------
    string selectedFile;
    //Grab the file name that is selected
    selectedFile = Convert.ToString(filesListBox.SelectedItem);
    //Open the file and assign a StreamReader to read the contents
    FileStream fsFileInfo = new FileStream(filePath + selectedFile, FileMode.Open, FileAccess.Read);
    StreamReader srFileInfo = new StreamReader(fsFileInfo);
    //Finally, display the entire contents of the file
    fileContents.Text = Convert.ToString(srFileInfo.ReadToEnd());
    }
    }
    }
    //--------------
    //-NO MORE CODE-
    //--------------
    0
  • 0

    Thanks thats great! I have now got a listbox that displays files from the specified location and a text box which displays the contents of the file when you press a button.

    However, when I try and read a certain type of file this error occurs:

    An unhandled exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll

    I deleted internal from the filepath string variable declaration which allowed it to read from a specified location and it diaplays the files in the list box but when I press the button to get the contents for one of those files I get that error.

    I found out how to read xml files but I don't know how to incorporate the selected items bit! I can read xml files if I specify the location but I want to be able to read any file that is selected. Can you help with this? This is the code I have used to read the xml

    TypeScript
    private void button12_Click(object sender, System.EventArgs e)
    {
    System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("c:\\xmlfile.xml");
    string contents = "";
    while (reader.Read())
    {
    reader.MoveToContent();
    if (reader.NodeType == System.Xml.XmlNodeType.Element)
    contents += "<"+reader.Name + ">\n\n";
    if (reader.NodeType == System.Xml.XmlNodeType.Text)
    contents += reader.Value + "\n\n";
    }
    this.listbox1.Items.Clear();
    addListItem(contents);
    }
    0
  • 0

    Try this:

    private void button12_Click(object sender, System.EventArgs e)
    {
       //Check the existence of the file
       if(!File.Exists("C:\xmlfile.xml")
       {
          MessageBox.Show("File not found error.", "Error Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
       }
       else
       {
          //Read the information from the file
          System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("C:\xmlfile.xml");
          string contents = "";
          while (reader.Read())
          {
             reader.MoveToContent();
             if (reader.NodeType == System.Xml.XmlNodeType.Element)
             contents += "<"+reader.Name + ">\n";
             if (reader.NodeType == System.Xml.XmlNodeType.Text)
             contents += reader.Value + "\n";
          }
          this.listbox1.Items.Clear();
      
          //For each node in contents
          foreach(string strItem in contents)
          {
             addListItem.Items.Add(strItem);
          }
       }
    }

    What was happening was it wasnt finding the file and there was no error handler to handle the exception and it just crashed. Now itll check for the existence of the file and if it doesnt exist, itll just give you a warning message and return you back to the form.
    As for adding items to the list box, you cannot add multiple items at the same time. Hence the foreach statement:

    Pseudocode:
    for each item in the list of collected items(contents), add the item to addList and continue until no more items exist, then exit.

    I certainly hope this helps!

    Brandon

    EDIT:

    You could also use an ArrayList to accomplish this with better divisions:

    private void button12_Click(object sender, System.EventArgs e)
    {
       //Check the existence of the file
       if(!File.Exists("C:\xmlfile.xml")
       {
          MessageBox.Show("File not found error.", "Error Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
       }
       else
       {
          //Initialize the ArrayList
          ArrayList[] contents = new ArrayList;

          //Read the information from the file
          System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("C:\xmlfile.xml");
          while (reader.Read())
          {
             reader.MoveToContent();
             if (reader.NodeType == System.Xml.XmlNodeType.Element)
             contents.Add(Convert.ToString("<" + reader.Name + ">"));
             if (reader.NodeType == System.Xml.XmlNodeType.Text)
             contents.Add(Convert.ToString(reader.Value));
          }
          this.listbox1.Items.Clear();
      
          //For each node in contents
          foreach(string strItem in contents)
          {
             addListItem.Items.Add(strItem);
          }
       }
    }

    Keep in mind I have no way to actually test this code right now, so it might have a few small glitches in it but nothing too big to fix :)

    0
  • 0

    Yet another great answer thankyou! The error handling was useful. I was wondering if there is a way to lead a text/xml document directly into a panel or frame given a specific location? Rather than getting the file and reading the xml and outputting the text in a certain format. If this could be done would this be easier? because the xml document would already be formatted and all the nodes could be seen?

    If not, or if I'm going to stick to the way I am doing it at the moment I need to know how to separate specific nodes or show certain information from the xml file. This is what my program is currently displaying when it reads the xml: (I need to get the <ErrorText>, <DateandTime> and <ProductID> How can I specify these? Below the following XML is the code I modified from your last post. Thanks again for taking the time to explain it!

    Kind Regards,

    Drew,

    GetOCSHub_Stock_Reservation_Response.xml on JCT 809
    ************************************************************************

    <MSG><MSG_HDR><MSG_CLASS><MNEMONIC>OCS<MSG_SUB_CLASS><MNEMONIC>STOCK_RESERVATION<SENDER>
    <SERVICE_AGENT><SERVICE_AGENT_ID>HUB<SERVICE_AGENT_REF>HUB<SERVICE_AGENT_ROLE><RECIPIENT><SERVICE_AGENT><SERVICE_AGENT_ID><SERVICE_AGENT_REF><SERVICE_AGENT_ROLE><EVENT><DATE_EVENT_OCCURRED>
    <DATE_MESSAGE_CREATED>08/06/2007 11:32:02<ERROR><OCS_ERROR_NUMBER>0<SYSTEM_ERROR_NUMBER><ERROR_TEXT><MSG_BODY><PRODUCTS><PRODUCT><CAPABILITY_STATUS>99<PRODUCT_ID>100024071
    <OCS_REF>
    072480907060800358-1<QTY_REQUESTED>
    1
    <QTY_RESERVED>
    -1
    <QTY_IN_STOCK>
    -1
    <MAX_QTY_RESERVABLE>
    -1
    <RESERVATION_REF>
    <RESERVATION_ADD_INFO_1>
    <RESERVATION_ADD_INFO_2>
    <SOURCE_SA_NAME>
    <RESERVER_SA_ID>
    <SLOTS>
    <HINT_RELATED_SERVICES>
    <DEL_SVC_EQUIV_PROD_IDS>
    <DEL_SVC_EQUIV_PROD_ID>
    983000038
    <DEL_SVC_EQUIV_PROD_ID>
    986000061
    <DEL_SVC_EQUIV_PROD_ID>
    986000079
    <DEL_SVC_EQUIV_PROD_ID>
    986000087

    C#
    private void JCT809_Click(object sender, System.EventArgs e)
    {
    //Check the existence of the file
    if(!File.Exists(@"\\jct809\c$\Program Files\unipower\WWWRoot\CustomerOrder\OCSHubXML\GetOCSHub_Stock_Reservation_Response.xml"))
    {
    MessageBox.Show(@"File not found error. Click 'run' in the start menu and type \\jct813\c$, Username jct813\administrator, Password terminator", "Error Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    else
    {
    //Read the information from the file
    System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(@"\\jct809\c$\Program Files\unipower\WWWRoot\CustomerOrder\OCSHubXML\GetOCSHub_Stock_Reservation_Response.xml");
    string contents = "";
    while (reader.Read())
    {
    reader.MoveToContent();
    if (reader.NodeType == System.Xml.XmlNodeType.Element)
    contents += "<"+reader.Name + ">\n";
    if (reader.NodeType == System.Xml.XmlNodeType.Text)
    contents += reader.Value + "\n";
    }
    this.textBoxXml.Clear();
    
    //For each node in contents
    string header = "GetOCSHub_Stock_Reservation_Response.xml on JCT 809";
    this.TillLabel.Text = "JCT 809";
    textBoxXml.Text = (header + Environment.NewLine + "************************************************************************"+ Environment.NewLine + Environment.NewLine + contents);
    }
    0
  • 0
    Try this solution:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Xml;

    namespace ExamplesApp
    {
        public partial class MainForm : Form
        {
            public MainForm()
            {
                InitializeComponent();
            }

            private void startButton_Click(object sender, System.EventArgs e)
            {
               //Check the existence of the file
               if(!File.Exists("xmlFile.xml"))
               {
                  MessageBox.Show("File not found error.", "Error Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
               }
               else
               {
                   //Try to read the information from the file
                   try
                   {
                       //Create a new instance of FileStream to contain file
                       FileStream infoFile = new FileStream("xmlFile.xml", FileMode.Open, FileAccess.Read);

                       //Create a new instance of StreamReader to read info contained in infoFile
                       StreamReader infoReader = new StreamReader(infoFile);

                       fileContents.Clear();
                       fileContents.Text = Convert.ToString(infoReader.ReadToEnd());
                   }
                   //If information cannot be read, throw error
                   catch (System.IO.IOException)
                   {
                       MessageBox.Show("Could not read file.", "Error Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
                   }
                }
            }
        }
    }
    //--------------
    //-NO MORE CODE-
    //--------------


    All that did was open the XML file and read the contents as if it were a plain text file, pretty simple. Im not sure if it was what you were looking for but thats what it sounded like you wanted :)

    Brandon

    0
  • 0

    My program already reads an xml file but I need it to be formatted,

    for example, return specifc information from the xml such as a specifc node and its contents. How would I specify that I want the following from an xml file?
    <StockReservation>text............................ </StockReservation>

    Thanks,

    0
  • 0
    I cant remember exactly how to do that, I do remember I did it in my address book application though so Ill get with you on it after lunch when I go see what I did. Im positive I have the answer, just cant remember right off hand. All the code that makes it work is in bits and pieces in my head, lol.
    0
  • 0

    Thanks again :) I have tried looking on the net for example code which didn't work.

    0