Solved

How to modify a C# console application to read input files that don't have recognizable names and process the correct file based on file contents?

Posted on 2010-09-20
8
692 Views
Last Modified: 2013-12-16
I am creating my first C# Console application using Visual Studio 2005.
I have 2 daily input files with file names like the following that have no file name extension and let's assume the 2 files reside on my C drive in the root directory.
The names of the 2 daily input files change all the time, so I cannot hardcode the name of the input files in my C# program.

File #1) C:\%Clfids%M_vcd_lfids%GXSSSHDinback%POLLABLE%005cnp0msg0004ot8v
File #2) C:\%Clfids%M_xml_lfids%GXSSSHDinback%POLLABLE%005cnotula0004oqql

The contents of File #1 starts out as follows and I want to igore this file:

II*     þ              “      Ç                            Æ                     Ç       !      ¶       ¾   (   

The contents of File #2 starts out as follows and I want to process this file's contents:

<?xml version="1.0"?>
<csc:CVision_Index_File
    xmlns:csc="http://c.csc.com/xml/CVision_Index_File">
<csc:header>
    <csc:version>1.0</csc:version>
    <csc:c_name>              </csc:c_name>
    <csc:input_req_file></csc:input_req_file>
</csc:header>
<csc:item>
    <csc:processing_date>20100915</csc:processing_date>
    <csc:item_sequence_number>000006</csc:item_sequence_number>
    <csc:account_number>0000000000001</csc:account_number>
    <csc:check_number>0000000</csc:check_number>
</csc:item>
----------------------------------------
A snippet of my C# code follows.

Do you know how the following code could be modified so as to read the contents of 2 daily input files, regardless of the file names of the input files and ignore the contents of the file that has unintelligible characters and process the file that starts out with the data records shown in File #2? The values shown in File #2 are static for the first 3 records, so you can key in on any of these records in File #2, so that you would know to process this particular file.

using System;
using System.Xml;
using System.IO;
namespace ReadXml1
{
     class Class1
     {
         static string GetFormattedValue(string strVal)
         {
             return strVal.Substring(0, strVal.Length - 2) + "." + strVal.Substring(strVal.Length - 2);
         }

         static void Main(string[] args)
         {
            int i = 0;
            string[,] arr1 = new string[1000,6];
            int iCheckNumber = 0;
            XmlTextReader reader = new XmlTextReader("C:\\h.xml");
            StreamWriter sw = new StreamWriter("C:\\output.txt");
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.Name == "csc:check_number")
                    {
                        iCheckNumber = iCheckNumber + 1;
                        arr1[i,0] = "COMMENT: CHECK NUMBER #" + iCheckNumber;
                        arr1[i,1] = "GROUP_FIELD_NAME:CheckNumber";
                        String e = reader.ReadElementContentAsString();
                        String formattedString = e.Substring(6, 3);
                        arr1[i,2] = "GROUP_FIELD_VALUE:" + e;                        
                                          }
                    if (reader.Name == "csc:routing_transit")
                    {
                        arr1[i,3] = "GROUP_FIELD_NAME:RoutingTransit";
                        arr1[i,4] = "GROUP_FIELD_VALUE:" + reader.ReadElementContentAsString();
                        arr1[i,5] = "GROUP_FIELD_NAME:BankName";
                        arr1[i,6] = "GROUP_FIELD_VALUE:HBANK";                  
                }                        
            }  
            for (int iter = 0; iter < i; iter++)
            {
                for (int j = 0; j < 6; j++)
                {
                    sw.WriteLine(arr1[iter,j]);
                }
            }          
            sw.Close();
            reader.Close();                
         }                  
     }
}

0
Comment
Question by:zimmer9
  • 4
  • 4
8 Comments
 
LVL 9

Accepted Solution

by:
shadow77 earned 500 total points
ID: 33722506
Assuming that:
* your XML file always begins with "C:\%Clfids%M_xml_lfids", and
* you clean the folder each day so that old versions of your files are not present,
try something like this.

It should return find one file f that is the XML file you want to process.

    DirectoryInfo dir = new DirectoryInfo(@"C:\%Clfids%M_xml_lfids*");

    foreach (FileInfo f in dir.GetFiles()) ProcessFile(f);

Open in new window

0
 

Author Comment

by:zimmer9
ID: 33724930
To avoid confusion, assume that the 2 daily files are placed in a folder named C:\BANKFILES and we know absolutely nothing about the naming convention of the 2 XML files. How would you process the files?
The file names are unpredictable but the folder C:\BANKFILES is cleaned out every day and 2 new files are moved into folder C:\BANKFILES
 
For example, tomorrow the file names are now:

1) C:\BANKFILES \%Ch%XSSSHDinback%POLLABLE%39fede005cnp0msg0004ot8v
2) C:\BANKFILES \%39f%Ch%MORGANDEANDISC_xml_lfids%GXSSSHDinback%fede0056mhe6p500b75tbu
0
 

Author Comment

by:zimmer9
ID: 33726816
I can't assume that a file name with the characters "xml" in it, is the file I need to process.
I really need to read the contents of the 2 files to determine which of the 2 files needs to be processed. The file that I need to process would contain records like the following and the 1st 3 records are ALWAYS as follows:

<?xml version="1.0"?>              THIS RECORD IS ALWAYS THE SAME
<csc:CVision_Index_File           THIS RECORD IS ALWAYS THE SAME
    xmlns:csc="http://c.csc.com/xml/CVision_Index_File">   THIS RECORD IS ALWAYS THE SAME
<csc:header>
    <csc:version>1.0</csc:version>
    <csc:c_name>              </csc:c_name>
    <csc:input_req_file></csc:input_req_file>
</csc:header>
<csc:item>
    <csc:processing_date>20100915</csc:processing_date>
    <csc:item_sequence_number>000006</csc:item_sequence_number>
    <csc:account_number>0000000000001</csc:account_number>
    <csc:check_number>0000000</csc:check_number>
</csc:item>
0
 
LVL 9

Expert Comment

by:shadow77
ID: 33727806
In that case, I would use this code, which will find both files.  The file you wish to ignore should cause an exception and will just be closed.

static void Main(string[] args)

{

    int i = 0;

    string[,] arr1 = new string[1000,6];

    int iCheckNumber = 0;



    DirectoryInfo dir = new DirectoryInfo(@"C:\BANKFILES\*");

    foreach (FileInfo f in dir.GetFiles())

    {

        XmlTextReader reader = null;

        StreamWriter sw = new StreamWriter("C:\\output.txt");

        try

        {

            reader = new XmlTextReader("C:\\h.xml");

            while (reader.Read())

            {

                if (reader.NodeType == XmlNodeType.Element)

                {

                    if (reader.Name == "csc:check_number")

                    {

                        iCheckNumber = iCheckNumber + 1;

                        arr1[i,0] = "COMMENT: CHECK NUMBER #" + iCheckNumber;

                        arr1[i,1] = "GROUP_FIELD_NAME:CheckNumber";

                        String e = reader.ReadElementContentAsString();

                        String formattedString = e.Substring(6, 3);

                        arr1[i,2] = "GROUP_FIELD_VALUE:" + e;                        

                    }

                    if (reader.Name == "csc:routing_transit")

                    {

                        arr1[i, 3] = "GROUP_FIELD_NAME:RoutingTransit";

                        arr1[i, 4] = "GROUP_FIELD_VALUE:" + reader.ReadElementContentAsString();

                        arr1[i, 5] = "GROUP_FIELD_NAME:BankName";

                        arr1[i, 6] = "GROUP_FIELD_VALUE:HBANK";

                    }

                }                        

            }  

            for (int iter = 0; iter < i; iter++)

            {

                for (int j = 0; j < 6; j++)

                {

                    sw.WriteLine(arr1[iter,j]);

                }

            }          

        }

        catch (XmlException ex)

        {

            // Handle XML exceptions

        }

        catch (Exception ex)

        {

            // Handle general exceptions

        }

        finally

        {

            sw.Close();

            if (reader != null) reader.Close();

        }

    }

}                  

Open in new window

0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:zimmer9
ID: 33728449
DirectoryInfo dir = new DirectoryInfo(@"C:\BANKFILES\*");

System.ArgumentException     {"Illegal characters in path."}
0
 
LVL 9

Expert Comment

by:shadow77
ID: 33729889
Sorry; I was a bit rushed this morning and did not test because I don't have your setup.

This should work:

	DirectoryInfo dir = new DirectoryInfo(@"C:\BANKFILES");

	foreach (FileInfo f in dir.GetFiles())

	{

	    XmlTextReader reader = null;

	    StreamWriter sw = new StreamWriter("C:\\output.txt");

	    try

	    {

	        reader = new XmlTextReader(f);

	        while (reader.Read())

Open in new window

0
 

Author Comment

by:zimmer9
ID: 33730594
Error      1      The best overloaded method match for 'System.Xml.XmlTextReader.XmlTextReader(System.Xml.XmlNameTable)' has some invalid arguments      \\msad\root\NA\NY\users\Z\Visual Studio 2005\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs      27      30      ConsoleApplication3

Error      2      Argument '1': cannot convert from 'System.IO.FileInfo' to 'System.Xml.XmlNameTable'      \\msad\root\NA\NY\users\Z\Visual Studio 2005\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs      27      48      ConsoleApplication3
0
 
LVL 9

Expert Comment

by:shadow77
ID: 33730631
reader = new XmlTextReader(f.FullName);
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Workbook link problems after copying tabs to a new workbook? David Miller (dlmille) Intro Have you either copied sheets to a new workbook, and after having saved and opened that workbook, you find that there are links back to the original sou…
The viewer will learn how to use a discrete random variable to simulate the return on an investment over a period of years, create a Monte Carlo simulation using the discrete random variable, and create a graph to represent the possible returns over…
This Micro Tutorial demonstrate the bugs in Microsoft Excel for Mac with Pivot Charts.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now