How can i read all the lines from a text file in specific places and use the data ?

string[] lines = File.ReadAllLines(@"c:\wmiclasses\wmiclasses1.txt");
for (int i = 0; i < lines.Length; i++)
if (lines[i].StartsWith("ComboBox"))
And this is how the text file content look like:
ComboBox Name cmbxOption
Classes Win32_1394Controller
Classes Win32_1394ControllerDevice
ComboBox Name cmbxStorage
Classes Win32_LogicalFileSecuritySetting
Classes Win32_TapeDrive
What i need to do is some things:
1. Each time the line start with ComboBox then to get only the ComboBox name from the line for example cmbxOption.
   Since i have already this ComboBoxes in my form1 designer i need to identify where the cmbxOption start and end and when the next ComboBox start cmbxStorage.
2. To get all the lines of the current ComboBox for example this lines belong to cmbxOption:
Classes Win32_1394Controller
Classes Win32_1394ControllerDevice
3. To create from each line a Key and Value for example from the line:
Classes Win32_1394Controller
Then the key will be Win32_1394Controller and the value will be only 1394Controller
Then the second line key Win32_1394ControllerDevice and value only 1394ControllerDevice
4. To add to the correct belonging ComboBox only the value 1394Controller.
5. To make that when i select in the ComboBox for example in cmbxOption the item 1394Controller it will act like i selected Win32_1394Controller.
For example in this event:
private void cmbxOption_SelectedIndexChanged(object sender, EventArgs e)
InsertInfo(cmbxOption.SelectedItem.ToString(), ref lstDisplayHardware, chkHardware.Checked);
In need that the SelectedItem will be Win32_1394Controller but the user will see in the cmbxOption only 1394Controller without the Win32_
This is the start of the method InsertInfo
private void InsertInfo(string Key, ref ListView lst, bool DontInsertNull)
That's why i need that the Key will be Win32_1394Controller but i want that the user will see in the ComboBox only 1394Controller without the Win32_

Hello,
Here is a running start on getting specific lines in the case lines starting with ComboBox. I took your data and placed it into a text file named TextFile1.txt in the bin\debug folder. Code below was done in
a console app.
using System;
using System.IO;
using System.Linq;
namespace ConsoleApplication1
internal class Program
private static void Main(string[] args)
var result =
from T in File.ReadAllLines(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TextFile1.txt"))
.Select((line, index) => new { Line = line, Index = index })
.Where((s) => s.Line.StartsWith("ComboBox"))
select T
).ToList();
if (result.Count > 0)
foreach (var item in result)
Console.WriteLine("Line: {0} Data: {1}", item.Index, item.Line);
Console.ReadLine();
Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my webpage under my profile but do not reply to forum questions.

Similar Messages

  • Reading a Random Line from a Text File

    Hello,
    I have a program that reads from a text file words. I currently have a text file around 800KB of words. The problem is, if I try to load this into an arraylist so I can use it in my application, it takes wayy long to load. I was wondering if there was a way to just read a random line from the text file.
    Here is my code, and the text file that the program reads from is called 'wordFile'
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    public class WordColor extends JFrame{
         public WordColor(){
              super("WordColor");
              setSize(1000,500);
              setVisible(true);
              add(new WordPanel());
         public static void main(String[]r){
              JFrame f = new WordColor();
    class WordPanel extends JPanel implements KeyListener{
         private Graphics2D pane;
         private Image img;
         private char[]characterList;
         private CharacterPosition[]positions;
         private int charcounter = 0;
         private String initialWord;
         private File wordFile = new File("C:\\Documents and Settings\\My Documents\\Java\\projects\\WordColorWords.txt");
         private FontMetrics fm;
         private javax.swing.Timer timer;
         public final static int START = 20;
         public final static int delay = 10;
         public final static int BOTTOMLINE = 375;
         public final static int buffer = 15;
         public final static int distance = 4;
         public final static Color[] colors = new Color[]{Color.red,Color.blue,Color.green,Color.yellow,Color.cyan,
                                                                          Color.magenta,Color.orange,Color.pink};
         public static String[] words;
         public static int descent;
         public static int YAXIS = 75;
         public static int SIZE = 72;
         public WordPanel(){
              words = readWords();
              setLayout(new BorderLayout());
              initialWord = getWord();
              characterList = new char[initialWord.length()];
              for (int i=0; i<initialWord.length();i++){
                   characterList[i] = initialWord.charAt(i);
              setFocusable(true);
              addKeyListener(this);
              timer = new javax.swing.Timer(delay,new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        YAXIS += 1;
                        drawWords();
                        if (YAXIS + descent - buffer >= BOTTOMLINE) lose();
                        if (allColorsOn()) win();
         public void paintComponent(Graphics g){
              super.paintComponent(g);
              if (img == null){
                   img = createImage(getWidth(),getHeight());
                   pane = (Graphics2D)img.getGraphics();
                   pane.setColor(Color.white);
                   pane.fillRect(0,0,getWidth(),getHeight());
                   pane.setFont(new Font("Arial",Font.BOLD,SIZE));
                   pane.setColor(Color.black);
                   drawThickLine(pane,getWidth(),5);
                   fm = g.getFontMetrics(new Font("Arial",Font.BOLD,SIZE));
                   descent = fm.getDescent();
                   distributePositions();
                   drawWords();
                   timer.start();
              g.drawImage(img,0,0,this);
         private void distributePositions(){
              int xaxis = START;
              positions = new CharacterPosition[characterList.length];
              int counter = 0;
              for (char c: characterList){
                   CharacterPosition cp = new CharacterPosition(c,xaxis, Color.black);
                   positions[counter] = cp;
                   counter++;
                   xaxis += fm.charWidth(c)+distance;
         private void drawThickLine(Graphics2D pane, int width, int thickness){
              pane.setColor(Color.black);
              for (int j = BOTTOMLINE;j<BOTTOMLINE+1+thickness;j++){
                   pane.drawLine(0,j,width,j);
         private void drawWords(){
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              drawThickLine(pane,getWidth(),5);
              for (CharacterPosition cp: positions){
                   int x = cp.getX();
                   char print = cp.getChar();
                   pane.setColor(cp.getColor());
                   pane.drawString(""+print,x,YAXIS);
              repaint();
         private boolean allColorsOn(){
              for (CharacterPosition cp: positions){
                   if (cp.getColor() == Color.black) return false;
              return true;
         private Color randomColor(){
              int rand = (int)(Math.random()*colors.length);
              return colors[rand];
         private void restart(){
              charcounter = 0;
              for (CharacterPosition cp: positions){
                   cp.setColor(Color.black);
         private void win(){
              timer.stop();
              newWord();
         private void newWord(){
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              repaint();
              drawThickLine(pane,getWidth(),5);
              YAXIS = 75;
              initialWord = getWord();
              characterList = new char[initialWord.length()];
              for (int i=0; i<initialWord.length();i++){
                   characterList[i] = initialWord.charAt(i);
              distributePositions();
              charcounter = 0;
              drawWords();
              timer.start();
         private void lose(){
              timer.stop();
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              pane.setColor(Color.red);
              pane.drawString("Sorry, You Lose!",50,150);
              repaint();
              removeKeyListener(this);
              final JPanel p1 = new JPanel();
              JButton again = new JButton("Play Again?");
              p1.add(again);
              add(p1,"South");
              p1.setBackground(Color.white);
              validate();
              again.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        remove(p1);
                        addKeyListener(WordPanel.this);
                        newWord();
         private String getWord(){
              int rand = (int)(Math.random()*words.length);
              return words[rand];
         private String[] readWords(){
              ArrayList<String> arr = new ArrayList<String>();
              try{
                   BufferedReader buff = new BufferedReader(new FileReader(wordFile));
                   try{
                        String line = null;
                        while (( line = buff.readLine()) != null){
                             line = line.toUpperCase();
                             arr.add(line);
                   finally{
                        buff.close();
              catch(Exception e){e.printStackTrace();}
              Object[] objects = arr.toArray();
              String[] words = new String[objects.length];
              int count = 0;
              for (Object o: objects){
                   words[count] = (String)o;
                   count++;
              return words;
         public void keyPressed(KeyEvent evt){
              char tempchar = evt.getKeyChar();
              String character = ""+tempchar;
              if (character.equalsIgnoreCase(""+positions[charcounter].getChar())){
                   positions[charcounter].setColor(randomColor());
                   charcounter++;
              else if (evt.isShiftDown()){
                   evt.consume();
              else{
                   restart();
              drawWords();
         public void keyTyped(KeyEvent evt){}
         public void keyReleased(KeyEvent evt){}
    class CharacterPosition{
         private int xaxis;
         private char character;
         private Color color;
         public CharacterPosition(char c, int x, Color col){
              xaxis = x;
              character = c;
              color = col;
         public int getX(){
              return xaxis;
         public char getChar(){
              return character;
         public Color getColor(){
              return color;
         public void setColor(Color c){
              color = c;
    }

    I thought that maybe serializing the ArrayList might be faster than creating the ArrayList by iterating over each line in the text file. But alas, I was wrong. Here's my code anyway:
    class WordList extends ArrayList<String>{
      long updated;
    WordList readWordList(File file) throws Exception{
      WordList list = new WordList();
      BufferedReader in = new BufferedReader(new FileReader(file));
      String line = null;
      while ((line = in.readLine()) != null){
        list.add(line);
      in.close();
      list.updated = file.lastModified();
      return list;
    WordList wordList;
    File datFile = new File("words.dat");
    File txtFile = new File("input.txt");
    if (datFile.exists()){
      ObjectInputStream input = new ObjectInputStream(new FileInputStream(datFile));
      wordList = (WordList)input.readObject();
      if (wordList.updated < txtFile.lastModified()){
        //if the text file has been updated, re-read it
        wordList = readWordList(txtFile);
        ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
        output.writeObject(wordList);
        output.close();
    } else {
      //serialized list does not exist--create it
      wordList = readWordList(txtFile);
      ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
      output.writeObject(wordList);
      output.close();
    }The text file contained one random sequence of letters per line. For example:
    hwnuu
    nhpgaucah
    zfbylzt
    hwnc
    gicgwkhStats:
    Text file size: 892K
    Serialized file size: 1.1MB
    Time to read from text file: 795ms
    Time to read from serialized file: 1216ms

  • How can I transfer all my photos from mb aperture file to a external hdd?

    The problem is it is taking too much of my internal memory therefore I want to transfer all my photos from mb to external. can somebody help me???

    More complete explanation:
    First make a Vault to an external drive as backup.
    Then from within Aperture:
    File Menu--> Relocate Masters.
    Next back up the  drive that the Masters were relocated to, because now you have a Referenced Masters Library so Masters are backed up (once) separately from the Library Vault backups.
    In the future back up originals (once) on external drives prior to import into Aperture or any other images app. I cannot overstate how important that is, and various manuals, texts, etc. present workflows that skip that critical step. Also back up the Aperture Library using Aperture's Vaults, which are designed for that purpose.
    A complete Referenced-Masters workflow follows. Note that for image security reasons Aperture is not involved until the end of the process:
    • Create a folder ("abc") for the incoming images. Easiest is to create the folder on the external hard drive where the Masters will permanently live, but Referenced Masters can be temporarily on the laptop's internal drive, then moved later as described above. I initially put Masters referenced on my MBP internal drive, then after backup and editing I use File Menu--> Relocate Masters to move the Masters to a permanent external drive location.
    • Connect a card reader with the camera card in it. The camera card should show on the desktop. If it does not show, restart the Mac with the reader and card still plugged in. You can of course use the camera directly in this step, but I do not recommend it. Obviously cameras like the iPad2 do require direct camera-to-computer uploading.
    • Drag the contents of the card's image folder(s) to the abc folder that you previously created on the hard drive.
    • Review the abc folder contents to be sure they all copied properly.
    • Software-eject the camera card.
    • Physically disconnect the camera card reader from the Mac. This step is important to help avoid all-too-common human error.
    • Again review the abc folder contents to be sure they are indeed all there (because stuff happens sometimes...).
    • Back up the abc folder contents on to another drive.
    • Review the files on the backup to be sure they all copied properly.
    • At any time after but not before the previous step you can reformat the camera card in-camera. Do not delete images on the card using the computer.
    • Start Aperture.
    • Import the images from folder abc into Aperture, selecting "Store Files: In their current location" on the right-hand side of the import window (important!).
    HTH
    -Allen Wicks

  • How can i transfer all my downloads from my ipod to my ipad2 if i used a different itunes account for my ipod

    i am trying to find a way to transfer my Ipod music and pictures to my Ipad2. My Ipod was synced on a different computer and itunes account then my I pad2. How would i save everything without syncing it and losing everything i have?

    If the music isn't purchased then you should be fine. Here is an application that will let you transfer the pictures from the iPod into iTunes on the laptop. This has been highly recommended here on this discussion site. There is a demo version that you can download to your laptop to see how you like it.
    http://www.wideanglesoftware.com/touchcopy/index.php?gclid=CPrX34O04qwCFQ1x5Qodl XHbnA

  • How can I add random mail signatures from a text file?

    I'm trying to add a different quote to every email that I write... is there a program or way for Mail to pluck and append a quote at random from a external file of quotes?  (I'm not talking about the standard "Random" feature built into Mail.)
    There must be one out there, but I can't find it.  I'm using Snow Leopard and Mail 4.5

    Hello,
    Here is a running start on getting specific lines in the case lines starting with ComboBox. I took your data and placed it into a text file named TextFile1.txt in the bin\debug folder. Code below was done in
    a console app.
    using System;
    using System.IO;
    using System.Linq;
    namespace ConsoleApplication1
    internal class Program
    private static void Main(string[] args)
    var result =
    from T in File.ReadAllLines(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TextFile1.txt"))
    .Select((line, index) => new { Line = line, Index = index })
    .Where((s) => s.Line.StartsWith("ComboBox"))
    select T
    ).ToList();
    if (result.Count > 0)
    foreach (var item in result)
    Console.WriteLine("Line: {0} Data: {1}", item.Index, item.Line);
    Console.ReadLine();
    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my webpage under my profile but do not reply to forum questions.

  • How can I create a Document object from a text file (myFile.txt)

    Hi everybody:
    Thank you for reading this message.
    I am trying to find a method to convert a text file ( I have it in a File object) to a Document object.
    I read the Java API but it is strange, I do not know if I have to create an AbstractDocument, it is really strange for me.
    Any comment is welcome,
    Regards,
    JB

    Document is an interface, and AbstractDocument is abstract, so you
    can't create either of those directly. Assuming you are dealing with a
    a plain text file, you could do something like
    // Not catching any exceptions that get thrown
    File file = /* file you already have */
    String eol = System.getProperty( "line.separator" );
    int eolLen = eol.length();
    FileReader reader = new FileReader( file );
    BufferedReader buffer = new BufferedReader( reader );
    PlainDocument doc = new PlainDocument();
    for ( String line = buffer.readLine() ; line != null ; line = buffer.readLine() ) {
        int len = doc.getLength();
        if ( len > 0 ) {
            doc.insertString( len, eol, null );
            len += eolLen;
        doc.insertString( len, line, null );
    }and now you have a document.
    : jay

  • Reading one line from a text file into an array

    i want to read one line from a text file into an array, and then the next line into a different array. both arays are type string...i have this:
    public static void readAndProcessData(FileInputStream stream){
         InputStreamReader iStrReader = new InputStreamReader (stream);
         BufferedReader reader = new BufferedReader (iStrReader);
         String line = "";          
         try{
         int i = 0;
              while (line != null){                 
                   names[i] = reader.readLine();
                   score[i] = reader.readLine();
                   line = reader.readLine();
                   i++;                
              }catch (IOException e){
              System.out.println("Error in file access");
    this section calls it:
    try{                         
         FileInputStream stream = new FileInputStream("ISU.txt");
              HighScore.readAndProcessData(stream);
              stream.close();
              names = HighScore.getNames();
              scores = HighScore.getScores();
         }catch(IOException e){
              System.out.println("Error in accessing file." + e.toString());
    it gives me an array index out of bounds error

    oh wait I see it when I looked at the original quote.
    They array you made called names or the other one is prob too small for the amount of names that you have in the file. Hence as I increases it eventually goes out of bounds of the array so you should probably resize the array if that happens.

  • I have an ancient laptop (from 2005) that has my entire music library. This laptop barely works and some keys don't type anymore. How can I get all this music transferred to another computer, or available to me on the cloud?

    I have an ancient laptop (from 2005) that has my entire music library. This laptop barely works and some keys don't type anymore. How can I get all this music transferred to another computer, or available to me on the cloud?

    No... do not move programs.
    About the iTunes library files
    Your iTunes library files track the media you add to iTunes, how you've organized it, and other information such as playlists. By default, these two files are in your iTunes folder:
    Mac OS X: /Users/username/Music/iTunes/
    Windows XP: C:\Documents and Settings\username\My Documents\My Music\iTunes\
    Windows Vista: C:\Users\username\Music\iTunes\
    Windows 7: C:\Users\username\My Music\iTunes\
    Windows 8: C:\Users\username\My Music\iTunes\

  • How can I move all my bookmarks from different Firefox profiles into one area to organize them and then place them into the different Firefox profiles?

    How can I move all my bookmarks from different Firefox profiles (would like to move whole bookmark folders at once if possible) into one area to organize them and then place them into the different Firefox profiles? This is all under one window user account, I am using windows 8.1. Even if you have information on how to do it on a different windows, it may still be helpful. Thanks for any input you have.

    Just a note about the difference between these two things:
    * "export" and "import" use an ancient HTML document format that all browsers can understand. When you import bookmarks, Firefox may place them into an Imported Bookmarks folder, or into Unsorted Bookmarks. This does not displace existing bookmarks, and Firefox does not automatically remove duplicates.
    * "backup" and "restore" use a more comprehensive JSON data file, which contains extra information about your bookmarks (such as tags) not contained in the traditional export file. HOWEVER, a restore completely replaces all existing bookmarks, so the restore feature cannot be used to merge in a set of additional bookmarks.
    Related support articles:
    * [[Export Firefox bookmarks to an HTML file to back up or transfer bookmarks]]
    * [[Import Bookmarks from a HTML file]]
    * [[Restore bookmarks from backup or move them to another computer]]
    Some users find the disk-based Windows Favorites folder a convenient way to organize bookmarks. If you do, too, and you do not need to preserve tags on your bookmarks, you could export each profile's bookmarks to HTML and import them all into IE11. Organize them in the Windows Favorites folder, then export from IE11 to HTML and import that file into each Firefox profile. See: [http://windows.microsoft.com/en-us/internet-explorer/add-view-organize-favorites].

  • My computer crashed and I lost everything. It was the only computer with Sync on it and I cannot get my recovery key: how can I get all my bookmarks from that Sync account?

    My computer crashed and I lost everything. It was the only computer with Sync on it and I cannot get my recovery key: how can I get all my bookmarks from that Sync account? I have a ton of bookmarks/saved password and the only way to get on sync is create a new recovery key and lose all of my information.
    Is there any way to get my stuff back without creating a new recovery key and losing all my old stuff?

    It has always been very basic to always maintain a  backup copy of your computer for just such an occasion.
    Use your backup copy to put everything back.

  • How can I transfer all my music from the apple ID account on my dad's computer to my new computer without burning like a hundred CD's?

    How can I transfer all my music from the apple ID account on my dad's computer to my new computer without burning like a hundred CD's?

    For non-iTunes purchases you need a third-party program like one of those discussed here:
    Recovering your iTunes library from your iPod or iOS device: Apple Support Communities

  • How can I transfer all iTunes purchases from one apple id to another

    How can I transfer all iTunes purchases from one apple id to another?

    Delmar Ford wrote:
    Don't agree. I have two accounts, one for work which I set up years ago and bought a few tracks. I've recently bought iPhone and iPad and created a home ID and wanted to transfer the old purchaces. Everyone says it can't be done, but I've done it.
    1. on the iPhone/iPad change your "store" Apple ID to the one you want ot transfer from.
    2. go into iTune on the device and download the purchaces.
    3. on you PC/Mac change the iTunes login to the same as the device's ID
    4. sync your device
    5. change both ID's back and the purchaces stay on both iTunes and your device.
    Delmar,
    The procedure you describe is putting content from two different IDs into a single library, which can readily be done.
    However, each item of purchased content will still be tied to the ID from which it was originally purchased, and they will be treated separately for purposes of Cloud, Match, Purchase History, etc.

  • How can I transfer all my info from my old mac to a new one?

    how can I transfer all my info from my old macbook to my mac mini?
    My Mac mini chash about one month ago and I got it back from apple, I didnt have a time michine back up for this one but in my old mac I have almost all my files, so I want to transfer all the data to the Mac mini with no problem

    You can use migration assitant which is located in the Utility Folder under Applications. The compters can be connected via ethernet, fire wire, or wifi. My recommendation is not to use wifi.
    You run migration assistant on both machines and you can choose to transfer everything or just data.
    Another way is to use migration assistant to restore from a time machine backup.

  • HT1296 How can I transfer all my photos from my Ipad Mini to my new MacBook Pro

    How can I transfer all my photos from my Ipad Mini to my new MacBook Pro
    I am facing problem while I connect to my iPad mini with MacBook Pro , it only sync photo from its taken by and from it camera roll only. It doesn't sync all the images... Like my all albums. All photos in library....

    To copy photos that were originally synced from a computer you will need a third-party app such as Simple Transfer which can copy them off via your wifi network. But as photos are 'optimised' when they are synced to the iPad, any that you then copy back to a computer may not be exactly the same as they originally were on your computer.
    You should also be able to copy albums that you've created directly on the iPad via apps such as Simple Transfer (though I haven't tried it)

  • I just bought a new ITOUCH 4th Generation how can i transfer all my apps from my old ITOUCH 2nd Generation? Is it possible?

    I just bought a new ITOUCH 4th Generation how can i transfer all my apps from my old ITOUCH 2nd Generation? Is it possible?I just bought a new ITOUCH 4th Generation how can i transfer all my apps from my old ITOUCH 2nd Generation? Is it possible?
    Thanks

    If you want to transfer app dat you need to restore the new iPod from the backup of the old iPod.  Restoring from backup will result in your new iPod being just like your old iPOd except you will have to reenter keychain items like passwords since those only get restore to the same device upon a restore.

Maybe you are looking for

  • Calendar Sync, Palm Zire 31 and Mac OS 10.4.6

    We just purchased several Palm Zire 31 handhelds because that model is one on Oracle's list as "certified" to work with Calendar Sync. However, I cannot seem to get it to sync properly to Oracle Calendar. Prior to installing Calendar Sync it synced t

  • Downsampling algorithm for JPG images in both PDF or automatic mode

    Hello, the question is: which algorithm is used when images are formatted by the Folio Builder in the Folio or Articles properties? My question is focused on the static images and I know that it would be better to resize images before placing them in

  • ITunes 7 attempting to sync all Podcast episodes regardless of selection

    I don't know if it's just me, but iTunes 7 seems to be ignoring which podcast episodes I have selected to sync and which I haven't, instead attempting to sync them all then erroring. I can get it to work if I only sync new episodes, but I like to kee

  • Suppress the item delivery schedule on PO  while printing

    Gurus Can anyone let me know if I can Suppress the item delivery schedule on PO  while printing specific to a user? Or any way how i can do that

  • Saving data problem

    we are using ISR in combination with adobe forms. we managed to get the data elements dynamic. But now I want to get the data fields end values and safe them in SAP. the code i am using is: try {      IPublicISR_Form.IMappedFieldsElement field =