Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
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
Medium Priority
?
707 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
8 Comments
 
LVL 9

Accepted Solution

by:
shadow77 earned 2000 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
NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

 
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
 

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

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Excel can be a tricky bit of software to get your head around. Whilst you’ll be able to eventually get to grips with the basic understanding of how to get by, there are a few Excel tips that not everybody will even know about let alone know how to d…
Do you use a spreadsheet like Microsoft's Excel?  Have you ever wanted to link out to a non excel file on your computer or network drive?  This is the way I found to do it!
The viewer will learn how to create two correlated normally distributed random variables in Excel, use a normal distribution to simulate the return on different levels of investment in each of the two funds over a period of ten years, and, create a …
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

730 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