简体   繁体   中英

Reading a text file into an array in C#

This is an extract from a text file that needs to be proccessed. What needs to be done is the program must read in this text file and format it to a specfication. The problem is i do not have much experiance working with text files. This is the sample input file.

BSA      Security Definition - Operator Report  Type 28


NBC 3RD QUARTER PROFILE REVIEW 2010
________________________________________________________________________________        


Operator:                 ABAZ095       
Number of entries:        149   
User selection:           Selected Items        

________________________________________________________________________________        


Search Criteria :-

    Operator Name   = BT%
    Approval Status = Any
    Enable Status   = Any
    One-time Pwd    = Any
    Profiles        =  
    Units           =  
    Printers        =  
    Terminals       =  

________________________________________________________________________________        

Operator ID           = BTA020          

Name                  = ASIA CHAMBEGA   
Active profile        = User_Disabled   
Enable status         = Disabled        
Re-enable date        = 31/12/36 00:00:00        
Approval status       = Approved        
Last changed          = 21/07/10 07:34:30       
Last sign-on          = 13/06/08 14:09:37        
Calculated pwd        = BD              
One-time password     = No              
Assigned unit         = None            



Operator ID           = BTAC002         

Name                  = A KALATA (NBC)  
Active profile        = User_Disabled   
Enable status         = Disabled        
Re-enable date        = 31/12/36 00:00:00        
Approval status       = Approved        
Last changed          = 31/05/10 14:04:41       
Last sign-on          = n/a
Calculated pwd        = B9              
One-time password     = No              
Assigned unit         = None            



Operator ID           = BTAK000         

Name                  = AISHA KEJO      
Active profile        = NLCB_R6.0_ACCESSCTRL    
Active profile        = NLCB_R6.0_VERAUT_MBE    
Enable status         = Enabled         
Re-enable date        = n/a
Approval status       = Approved        
Last changed          = 12/07/08 08:10:47       
Last sign-on          = 19/07/08 08:08:58        
Calculated pwd        = 8A              
One-time password     = No              
Assigned unit         = NLCB            



Operator ID           = BTAL001         

Name                  = AMANDUS LIPILI  
Active profile        = User_Disabled   
Enable status         = Disabled        
Re-enable date        = 31/12/36 00:00:00        
Approval status       = Approved        
Last changed          = 01/07/10 08:39:03       
Last sign-on          = 11/11/09 08:25:07        
Calculated pwd        = 4B              
One-time password     = No              
Assigned unit         = None            

When processed the output file should look as follows:

BTAK000, AISHA KEJO, NLCB_R6.0_ACCESSCTRL
BTAK000, AISHA KEJO, NLCB_R6.0_VERAUT_MBE

As you can see, all the data needs to be pulled in but only Operator ID, name and active profile needs to be output. Everytime operator id if found in the file, the result needs to be printed to a new line. If the user has more than 1 active profile, the operator id and name and profile must be outputted to a new line. If the user has a disabled profile the data must be ignored. As you can see from the example the first to units are ignored because they are disabled. The user with the enabled satatus is the example. As you can see with the output example.

My idea is to pull the data into an array but only output the operator id, name and profile. How do I do this?

This is what I have so far:

Console.WriteLine("Enter Input File Location: " + "\n");

            //Reads path specifed by the user for input.
            string t = File.ReadAllText(Console.ReadLine());

            //Splits file where there is an equals sign.
            t = t.Replace("=", "");
            //Removes all tabbed spaces.
            t = t.Replace("\t", "");
            //Removes any new lines.
            t = t.Replace("\n", ",");
            //Removes blank spaces.
            t = t.Replace(" ", "");
            //Removes the Underscore.
            t = t.Replace("_", "");

            //Removes any leading or trailing whitespaces.
            t = t.Trim(',');

            //Writes formatted file to a pre defined ouput file's location.
            File.WriteAllText(@"C:/3rd Quarter1.txt", t);

With a textreader you can read every line by calling the ReadLine method of TextReader.

You do this in a while(!textreader.EndOfFile)

For each line you can search for specific characters --> search for the = and do something with the text behind it.

You can also check if the line starts with Operator ID

you could use a Regex to find the stuff you are looking for..

start by loading the entire file into a stream. then use a regex like this:

@"Operator ID = (.+?) Name = (.+?) Active profile = (.+?) Enable status "

will find all posts, then you ofc need to do another regex check on array to extract the activeProfiles (and to see if there is more than 1)

something like this:

@"Active profile = (.+?) "

disclamer.. you might need to modify the regex to fit what the streamreader actually puts into the stream.

Here is an nice tool to check your reqex's

EDIT: here is a sample of how the program could look like:

static void Main(string[] args)
    {
        string path = @"c:\test.txt";
        string t = File.ReadAllText(path);
        string pattern1 = @"OperatorID=(.+?),,Name=(.+?),(.+?),Enablestatus";
        Regex rgx = new Regex(pattern1);

        //Removes all tabbed spaces.
        t = t.Replace("\t", "");
        //Removes any new lines.
        t = t.Replace("\n", ",");
        //Removes blank spaces.
        t = t.Replace(" ", "");
        //Removes the Underscore.
        t = t.Replace("_", "");
        t = t.Replace("\r", "");

        MatchCollection matches = rgx.Matches(t);
        List<string[]> test = new List<string[]>();
        foreach (var match in matches)
        {
            string[] newString = match.ToString().Split(new string[] { @"OperatorID=", @",,Name=", @",Activeprofile=", @",Enablestatus",  }, StringSplitOptions.RemoveEmptyEntries);

            for (int i = 3 ; i <= newString.Length; i++)
            {
                test.Add(new string[] { newString[0], newString[1], newString[i - 1] });
            }

        }

        foreach (var line in test)
        {
            Console.WriteLine("ID: {0}\nName: {1}\nActive Profile: {2}\n", line[0], line[1], line[2]);
        }

        Console.ReadKey();

Didn't pay alot of attention to details in this tho :)

EDIT: To add the results to a file:

        using (StreamWriter myWriter = new StreamWriter(@"c:\testOutput.txt"))
    {

        foreach (var line in test)
        {
            myWriter.WriteLine("ID: {0}", line[0]);
            myWriter.WriteLine("Name: {0}", line[1]);
            myWriter.WriteLine("Active Profile: {0}", line[2]);
            myWriter.WriteLine();


        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM