Get specific Strings from File

Good morning to every one.
I 've got a text file which contains a customer number and an order number, coded as we see in the picture below:
I am trying to develop a tool in Visual Studio, which it reads the file line-by-line and fills a listbox, with the order_number and the customer number. From the file above, I know that the order number are the digits on the first 'column' after the leading-zeros,
until '/', and the customer number are the digits without zeros in the 'third' column before 'CUSTOMER_NUMBER'. My form looks like:
The problem is, that the number of before the fields in file, are not equal in every line.
So, my question is how I can retrieve the 'order number' and 'customer number' from the text file and copy the results to list box, after clicking on 'Get Strings' button, like:
359962656   2238914
359562804   2238914
etc...
I attach my code here:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace ReadStringFileApp
public partial class frmMain : Form
public frmMain()
InitializeComponent();
OpenFileDialog openfile = new OpenFileDialog();
//openfiledialog to pickup filename
private void btnFindFile_Click(object sender, EventArgs e)
openfile.Filter = "Text|*.txt";
if (openfile.ShowDialog() == DialogResult.OK)
lbxResults.Items.Clear();
txtFilepath.Text = openfile.FileName.ToString();
//get strings from file
private void btnGetStrings_Click(object sender, EventArgs e)
//check if there is a file path on textbox
if (txtFilepath.Text == "")
MessageBox.Show("No File Select. Please select a file", "Error File Name", MessageBoxButtons.OK, MessageBoxIcon.Error);
btnFindFile.Focus();
return;
//create list for all lines inside file
List<string> lines = new List<string>();
string line;
using (StreamReader r = new StreamReader(@txtFilepath.Text))
while ((line = r.ReadLine()) != null)
string ordernum;//string for order number
string customer;//string for customer number
//line = ordernum + "\t" + customer; //concatenate results to fill the list box
lbxResults.Items.Add(line);
r.Close(); //close file
private void btnExportToFIle_Click(object sender, EventArgs e)
//check if listbox is empty
if (lbxResults.Items.Count == 0)
MessageBox.Show("Result List is empty! Choose a file to proceed.", "Error Result List", MessageBoxButtons.OK, MessageBoxIcon.Error);
btnGetStrings.Focus();
return;
//read listbox contents and parse to a list object
List<string> list = new List<string>();
foreach (String i in lbxResults.Items)
list.Add(i);
//Create a file in c: with results
File.WriteAllLines(@"C:\export-test.txt", list, Encoding.Default);
MessageBox.Show("File export completed!", "File Export", MessageBoxButtons.OK, MessageBoxIcon.Information);
Thank you in advanced

@ Joel Engineer
and@
Val10
I combined your responses and I get my results correctly. I attached the code I rewrite for further use:
private void btnGetStrings_Click(object sender, EventArgs e)
//check if there is a file path on textbox
if (txtFilepath.Text == "")
MessageBox.Show("No File Select. Please select a file", "Error File Name", MessageBoxButtons.OK, MessageBoxIcon.Error);
btnFindFile.Focus();
return;
//create list for all lines inside file
List<string> lines = new List<string>();
string line;
using (StreamReader r = new StreamReader(@txtFilepath.Text))
while ((line = r.ReadLine()) != null)
string order_customer;
Regex reg = new Regex("0*");
//set an string array, to split the file in columns positions, defining the characters
string[] daneio = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
//get order number from the first column
var ordernum_zeros = reg.Match(daneio[0]).Value;
daneio[0] = daneio[0].Replace(ordernum_zeros, String.Empty);
daneio[0] = daneio[0].Substring(0, daneio[0].IndexOf("/"));
//get customer column, without zeros
var customer_zeros = reg.Match(daneio[5]).Value;
daneio[2] = daneio[2].Replace(customer_zeros, String.Empty);
daneio[2] = daneio[2].Substring(0, daneio[5].IndexOf("CUSTOMER_NUMBER"));
//combine the result in listbox
order_customer = daneio[0] + "\t" + daneio[2];
lbxResults.Items.Add(order_customer);
r.Close(); //close file
Thank you for your help!

Similar Messages

  • Using a script to get specific itens from a dvd

    How can I get specific itens from a dvd using a list of archives.
    for example: I have a list exel ou text containing the files I'd like to extract from this dvd ...Is it possible? put this list working to copy these files?
    thank you very much.....

    If you're a professional photographer with 50,000 pictures stored now and more coming all the time, you need to forget about using iPhoto and get yourself some professional-quality digital asset management software. iPhoto is not meant for people like you, and instead of providing a simple, elegant one-stop answer to all your needs, iPhoto is actually complicating your life.
    You need an application that will:
    - catalog ALL your images and keep track of where they are, no matter how many DVDs, folders, partitions or hard drives they're spread over;
    - display thumbnails of ALL of them, even when the DVD that contains them is not present in any drive, so you can select all the ones you want for a project;
    - find and copy (or export) the originals of all the files you've selected in the browser window, even if it means prompting you to insert the necessary DVDs for all of them.
    I suggest Googling "digital asset management software Macintosh" and seeing what turns up. I used to use an old version of Extensis Portfolio, and even that would have been better for your purposes than iPhoto is.

  • How to Read specific data from file and do a calculation and display on the output

    FYI: Below is the function use for the writing:
    -OpenFile(use ASCII)
    -sprintf
    -WriteFile
    Example: Output from the doc file
    …EndTime: 09:34:48 program time: 0.567663 sec
    …EndTime: 09:36:48 program time: 0.666666 sec
    My objective is to read data 0.666666 (FYI: is last sentence of the file) to do some calculation. How can we read specific data(specific location) from file..
    Any advice or help?
    What is the function needed?

    I would consider counting line feeds and checking for end-of file to isolate the last line, which then can be read using fscanf...
    Have a look at getc...
    character = fgetc ( stream );
    if ( character == '\n' ) // new line
    if ( character == EOF ) // end-of-file

  • How to read a string from file & assign the val to a variable in batch file

    Hi,
    How to read a string from a file and assign the value to a variable then return the value to the screen in windows batch file?
    Any suggestions?
    thanks.

    Unless this is a homework question then I don't see the purpose of doing this, but....
    You should be looking a the supplied package utl_file to get the string out of the file, dbms_output to display the string and then google windows batch/command files calling sqlplus to execute your program.
    Andre

  • Help with deleting multiple strings from file.......

    I am trying to delete the same string that may appear multiple times in the file. Here is the output to the screen. Here is the code. I have been researching the delete method it says that I have to start at an index position in the string but how would I find out where the multiples strings reside in the file? I am getting the feeling that it won't work for my purpose..???? I am trying to delete all ot the strings "a string of data3" from the file.
    Output
    C:\TestRead>java StringDelete
    Temp String file_data-------- a string of data3a string of data2a string of data
    1a string of data3a string of data2a string of data1a string of data3
    Just A Blank Line
    Just A Blank Line
    Just A Blank Line
    String toDelete-------- a string of data3
    Just A Blank Line
    Just A Blank Line
    Just A Blank Line
    String toDelete-------- a string of data2
    Just A Blank Line
    Just A Blank Line
    Just A Blank Line
    String toDelete-------- a string of data1
    Just A Blank Line
    Just A Blank Line
    Just A Blank Line
    String toDelete-------- a string of data3
    Just A Blank Line
    Just A Blank Line
    Just A Blank Line
    String toDelete-------- a string of data2
    Just A Blank Line
    Just A Blank Line
    Just A Blank Line
    String toDelete-------- a string of data1
    Just A Blank Line
    Just A Blank Line
    Just A Blank Line
    String toDelete-------- a string of data3
    Just A Blank Line
    Just A Blank Line
    Just A Blank Line
    Code:
    import java.io.*;
    public class StringDelete
    public static void main(String [] args)
    try
    FileInputStream fis = new FileInputStream("TestFile.txt");
    DataInputStream in = new DataInputStream(fis);
    StringBuffer file_data = new StringBuffer();
    while(in.available() > 0)
    String temp = in.readUTF(); // read in a string from the file
    file_data.append(temp); // append it to the buffer
    System.out.println("Temp String file_data-------- " + file_data);
    System.out.println("Just A Blank Line");
    System.out.println("Just A Blank Line");
    System.out.println("Just A Blank Line");
    boolean keepGoing = true;
    while(keepGoing)
    String toDelete = file_data.substring(0, "a string of data3".length());
    System.out.println("String toDelete-------- " + toDelete);
    System.out.println("Just A Blank Line");
    System.out.println("Just A Blank Line");
    System.out.println("Just A Blank Line");
    if(toDelete == null || toDelete.equals("") )
    keepGoing = false;
    else
    file_data.delete(0,"a string of data3".length());
    catch(IOException e)
    e.printStackTrace();

    Here is the output. I am trying to get each part to work before I go on to the next part that is why some code is commented out.
    I need help to know why string "a string of data3" is not deleted in the towrite string??
    Output:
    C:\TestRead>java NewStringDelete
    String v after remove [ &#9668;a string of data3 &#9668;a string of data2 &#9668;a string of data1
    &#9668;a string of data3 &#9668;a string of data2 &#9668;a string of data1 &#9668;a string of data3]
    String towrite after remove &#9668;a string of data3 &#9668;a string of data2 &#9668;a string of
    data1 &#9668;a string of data3 &#9668;a string of data2 &#9668;a string of data1 &#9668;a string of data
    3
    Code:
    import java.util.Vector;
    import java.io.*;
    public class NewStringDelete
         public static void main(String [] args)
              //String ls = System.getProperty("line.separator");
              //File file;
              Vector v=new Vector();
         try{
              BufferedReader br=new BufferedReader(new FileReader ("TestFile.txt"));
              String s;
              while ((s=br.readLine())!=null)
                   {v.addElement(new String(""+s));}
                        br.close();
         catch(IOException e)
                   e.printStackTrace();
    /*now you have a Vector containing String objects..*/
         String remove = ("a string of data3");
         String towrite="";
    System.out.println("String v after remove " + v);     
         for (int i=0; i<v.size();i++)
              String ss = (String)v.elementAt(i);
              if (ss.equalsIgnoreCase(remove)){continue;}
              //     towrite=towrite+ss+ls;
                   towrite=towrite+ss;
    System.out.println("");               
    System.out.println("");               
    System.out.println("String towrite after remove " + towrite);                    
    /*do filewrite*/
    //try{
    // FileWriter fw=new FileWriter(TestFile.txt);
    // fw.write(towrite);
    // fw.close();
    // catch(IOException e)
    //               e.printStackTrace();

  • Getting specific values From a database in Java

    Hey,
    I'm using XE and building an application in Java to do basic CRUD operations on the database.
    One of these operations is searching for a customer by last name (which runs fine) and the result of the query (a customer ID, a first name, and a last name) is displayed in a JTable. I want to be able to click on the record I need and use the customer ID to do an insert on another table CUSTOMER_PURCHASES which maps purchases to customers.
    How do I go about doing this knowing that customer ID is an auto-incremented number (using a SEQUENCE)?
    I thought about creating a variable in Java of type String called customerID and initialize it like this: String customerID = "CUSTOMER_SEQUENCE.nextval"
    But by doing this, I suspect that I'll be getting the next available customerID, not the one from the record I selected.
    Can anybody suggest a workaround or lead me in the right direction?
    Thank you in advance for the help and sorry about the long post, but I'm a newvbie to this field.

    As per raychen's advice, I was able to get the image from the database and bring it over into JavaFX.
    In my java class I retrieved the image as follows:
            BufferedImage image = null;  //Buffered image coming from database
            InputStream fis = null; //Inputstream
            try{
                ResultSet databaseResults;  //Returned results from DB
                stmt = conn.createStatement(); //Create the SQL statement
                databaseResults= stmt.executeQuery("SELECT * FROM mydb.`user` WHERE userID = 'username';"); //Execute query
                fis = blah.getBinaryStream(3);  //It happens that the 3rd column in my database is where the image is stored (a BLOB)
                image = javax.imageio.ImageIO.read(fis);  //create the BufferedImaged
            } catch (Exception e){
                     //print error if caught
           return image  //My function returns a BufferedImage objectSo in JavaFX, depending on how you have it set up, you essentially get the returned BufferedImage and create the image as follows:
    var bufferedImage : BufferedImage = theJavaFunctionThatReturnsABufferedImage();
    var newImage : Image = javafx.ext.swing.SwingUtils.toFXImage(bufferedImage);  //BufferedImageCheers and Happy New Year.

  • POWER QUERY Get External Data From File From Folder (Excel 2013)

    Hi,
    Beginner's question :
    What could be the use of the query on a folder : we just get a list of files with their path. What can we do with that?
    Thanks

    Hi,
    Do you want to combine data from multiple Excel Files in the same folder path into one table? If I understand correct, we can add a custom column to import the data.
    After we getting a list of files with their path, the Query Editor window will activate to show you a table containing a record for each file in the chosen directory. These will provide our function with the needed FilePath and FileName parameters. 
    Function sample: File name([Folder path],[Field name]
    For more detailed steps, please see the article:
    http://datapigtechnologies.com/blog/index.php/using-power-query-to-combine-data-from-multiple-excel-files-into-one-table/
    Please Note: Since the web site is not hosted by Microsoft, the link may change without notice. Microsoft does not guarantee the accuracy of this information.
    George Zhao
    TechNet Community Support
    It's recommended to download and install
    Configuration Analyzer Tool (OffCAT), which is developed by Microsoft Support teams. Once the tool is installed, you can run it at any time to scan for hundreds of known issues in Office
    programs.

  • How to get specific rows from the vo or Iterator in the backing bean?

    Hi,
    I have to get the specific number of rows from iterator in the backing bean. means i want to get the records from the VO or Iterator only from 5 th record to 10th record its like rownum in SQL.
    We can use rownum in VO sql query. but there would be a performance issue with that ...
    SO i am trying to get the rows from ADF Iterator once we fetch from DB.
    Is it possible to do that ?
    Do we have any way to set the pointer to the VO/Iterator like setFirst() and after that setMaxResult to retrun the rows between first and maxresult..
    Thanks

    If this is for pagination, then af:table offers pagination by design when you set accessmode=RangePaging or RangePagingIncremental in VO. Paginated queries are fired when scroll down in the table. Explore this option before you try out any custom solution
    To answer the question,
    Note: same logic i have implpemented ADF with EJB ..In EJB Query class we have setFirst(int) and setMaxResult(int) methods...simply i did setFirst(30) and setMaxResult(10)..It worked fine...Theoretically speaking the same can be achieved by setting setRangeStart() on the viewobject(which in turn sets to the default rowset) and by setting max fetch size on VO + accessmode=RangePaging. However when you use table with ADF binding, these will be overridden by the binding layer. If you are not using ADF binding, then the above is same as what you did for JPA entity. Other option is, you build expert mode VO with rownum for this special case, which will work if you dont need to set accessmode=RangePaging for VO.

  • How can I get specific URLs from outlook to open in firefox where IE is my default browser

    I require to open specific URLs from outlook to be opened in Firefox. However, IE will be my default browser.

    Try this tutorial ;)
    http://support.mozilla.com/en-US/kb/Remembering+passwords

  • Trying to get the string from javax.xml.transform.Source

    I have a SOAP client that will submit a string of data to a url and return an xml string back. It works ok besides that last part.
    I found on another site someone took the returned XML and printed it to the system print box. I want to just get the string out to a variable to pass back..
    This chunk works:
    TransformerFactory tff = TransformerFactory.newInstance();
    Transformer tf = tff.newTransformer();
    Source sc = rp.getSOAPPart().getContent();
    StreamResult result = new StreamResult(System.out);
    tf.transform(sc, result);
    System.out.println();Instead of this I just want to catch the XML string in a String variable. Thanks for the help.

    Instead of giving your StreamResult System.out, give it a StringWriter. You can then call toString on the StringWriter, and get what you're after
    StringWriter output = new StringWriter();
    TransformerFactory.newInstance().newTransformer().transform(source, new StreamResult(output));
    String xmlResult = output.toString();

  • How to get specific character from a string

    I have a value such as: 0-5 or 123-30. This is a combination
    from 2 different IDs.
    All I need is to get the number on the right (5 from 0-5 OR
    30 from 123), any number on the right of the "-" character not
    including
    the "-"
    I'm not sure what ColdFusion function can I use safely.
    I said safely since all I can find is either Left or Right
    functions. With these 2 functions, I need to specify the number of
    character to extract while in my case the application is growing so
    the ID may currently be only 1 digit each (0-5) but later it may
    grow longer (123-5677).
    If anyone know the function, please help me. Thank you!

    Something like this?
    Mid(string, Find("-",string)+1 ,
    Len(string)-Find("-",string))
    Since
    Mid(string, start, count)
    and
    Len(string or binary object)
    and
    Find(substring, string [, start ])
    Or perhaps ....
    ListLast(string, "-")
    since
    ListLast(list [, delimiters ])
    Phil

  • Unable to get the filename from file upload UI element

    Hi,
    I added a FileUpload UI element.
    I created an attribute of type resource , assigned to the resource property of the file upload element.
    I created an action button called upload and added the following code.
    try {
           IWDResource resource = wdContext.currentContextElement().getFileupload();
          } catch (Exception e) {
             e.printStackTrace();
    when I debug to see the value of resource it is null.
    Please let me know where I am going wrong.
    Regards,
    Narayani

    Hi,
    Check if there are any space characters in your uploading path (file path).
    First try to upload a file without any space characters in the uploading path(file path). If the problem is with the space characters then use the below encoding & decoding to resolve that issue.
    Encoding while uploading the file:
    // Getting the file resource
    IWDResource resource = element.getCtx_va_FileResource();
    //Getting the resource name
    String resourceName = resource.getResourceName();
    //Encoding the resource name
    String encoderesourceName = java.net.URLEncoder.encode(resourceName,"UTF-8");
    Again while downloading you can use decoder.
    Hope this helps to resolve your issue.
    See this below link.
    Re: File Upload Problem
    Try this encoding even if there are no space characters.
    Regards,
    Charan

  • Getting a String from an applet method

    I'm writing a page where a user enters the location of a local file and lets an applet calculate a binary hash of the file contents. I want the applet to give the hash string back to an empty textfield.
    The code I'm using is:
    <script language="JavaScript">
    function hash() {
    var test;
    test = document.FtpApplet.hash('E:\downloadz\mysql-4.0.12-win.zip');
    document.form.hash.value = test;
    </script>
    <FORM name="FTForm" method="post" action="#">
    <input type="button" value="Send" onClick="document.FtpApplet.upload();"><br>
    <input type="button" value="Hash" onClick="hash()"><br>
    <input type="text" name="hash"> ...
    My applet contains a ordinary public method giving back a string.
    In IE6 I get a runtime error pointing to the hash() function. In Netscape7/Mozilla 1.3 nothing happens at all. I'm using the latest version of the java plug-in in all my browsers.
    Could anyone help me out?

    You should try to find a javascript forum.

  • Converting string from file to array

    I'm new to LabVIEW and have been thrown into the middle of a project, so I need to get some code working fast! Can someone help me understand why the VI I've attached isn't working? I want to have a text file that contains a list of integers that will be used to reference particular elements in arrays within my program. I tried to follow an example I found, but the output that should be an array is coming out as a scaler. Any help would be super appreciated! Thanks!
    Solved!
    Go to Solution.
    Attachments:
    string_to_array.vi ‏9 KB
    exp.txt ‏1 KB

    First, let's explain the reason for your error: The reason why it's happening is that you're trying to do two different things at the same time. You're auto-indexing the array and you're trying to index the array inside the loop. When you wire an array to a for loop it auto-indexes the loop. Meaning LabVIEW knows how many times to run the loop - there is no need to wire to the N terminal. Also, the wire inside the loop will be an instance of the element of the array, not the array. So, the wire inside the loop is a scalar. Thus, the reason for the broken wire - you can't index a scalar.
    Also, I'm not sure what you're trying to do with the indexing of the one element of the cluster. The cluster is empty, so there's nothing to index. Presumably the file is there to tell you which elements to pull out from the "Amp2" array from the cluster. If so, remember that auto-indexing works both ways. If you connect an "outbound" wire to the edge of a loop it auto-indexed there as well, meaning the output will be an array.
    Please read the LabVIEW Help on auto-indexing.
    Now, given all of that, here is what your code should look like:
    Note the use of the Read From Spreadsheet File VI. It makes your life easier.
    Attachments:
    fixed code.png ‏22 KB

  • How to get tree structure from file list?

    I have got following rows from my select query presenting a folder structure:
    PATH
    /KING/JONES/SCOTT
    /KING/JONES/SCOTT/ADAMS
    /KING/JONES/FORD
    /KING/JONES/FORD/SMITH
    /KING/BLAKE
    /KING/BLAKE/ALLEN
    /KING/BLAKE/WARD
    /KING/BLAKE/MARTIN
    /KING/BLAKE/TURNER
    /KING/BLAKE/JAMES
    /KING/CLARK
    /KING/CLARK/MILLER
    /PALO/TEMP
    On base of this data I need to build tree in my application by effecient way.
    Therefore i would like to achieve data (SELECT with two columns) as bellow:
    FOLDER        PARENTFOLDER
    KING     NULL
    JONES   KING
    SCOTT  KING/JONES
    ADAMS  KING/JONES/SCOTT
    FORD     KING/JONES
    SMITH    KING/JONES/FORD
    BLAKE    KING
    ALLEN    KING/BLAKE
    WARD    KING/BLAKE
    MARTIN  KING/BLAKE
    TURNER  KING/BLAKE
    JAMES    KING/BLAKE
    CLARK     KING
    MILLER    KING/CLARK
    PALO      NULL
    TEMP      PALOIs this possible to do it on SQL level(not PL SQL)?
    Thanks

    Perhaps something like this?
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select '/KING/JONES/SCOTT' as path from dual union all
      2             select '/KING/JONES/SCOTT/ADAMS' from dual union all
      3             select '/KING/JONES/FORD' from dual union all
      4             select '/KING/JONES/FORD/SMITH' from dual union all
      5             select '/KING/BLAKE' from dual union all
      6             select '/KING/BLAKE/ALLEN' from dual union all
      7             select '/KING/BLAKE/WARD' from dual union all
      8             select '/KING/BLAKE/MARTIN' from dual union all
      9             select '/KING/BLAKE/TURNER' from dual union all
    10             select '/KING/BLAKE/JAMES' from dual union all
    11             select '/KING/CLARK' from dual union all
    12             select '/KING/CLARK/MILLER' from dual union all
    13             select '/PALO/TEMP' from dual
    14            )
    15  --
    16  -- END OF TEST DATA
    17  --
    18  select distinct substr(path,instr(path,'/',1,rn)+1,decode(instr(path,'/',1,rn+1),0,length(path)+1,instr(path,'/',1,rn+1))-instr(path,'/',1,rn)-1) as folder, substr(path,2,instr(path,'/',1,rn)-2) as parent
    19  from t
    20       cross join (select rownum rn from dual connect by rownum <= (select max(length(regexp_replace(path,'[^/]'))) from t)) x
    21* where instr(path,'/',1,rn) > 0
    SQL> /
    FOLDER                  PARENT
    BLAKE                   KING
    SCOTT                   KING/JONES
    JAMES                   KING/BLAKE
    MARTIN                  KING/BLAKE
    SMITH                   KING/JONES/FORD
    KING
    WARD                    KING/BLAKE
    ADAMS                   KING/JONES/SCOTT
    FORD                    KING/JONES
    TURNER                  KING/BLAKE
    MILLER                  KING/CLARK
    PALO
    TEMP                    PALO
    JONES                   KING
    CLARK                   KING
    ALLEN                   KING/BLAKE
    16 rows selected.
    SQL>

Maybe you are looking for