C# EDI Parser – Using RegEx Capture to Xref PO to Filename

This C# code fragment illustrates how to use the RegEx Captures collection within RegEx Groups.

I needed the ability to read all files in a directory, and build a CSV to cross reference the PO number to the EDI file it was in.

<pre>
            //Pattern we want, but then escape all the ^ signs  "REF^BM^(\d*)~";
            string strRegExPattern856 = @"REF^BM^(\d*)~".Replace("^", @"\^");
</pre>

<pre>
public static void parseFile(string strDirectoryName, string filemask, string prefix, 
                             string filetype, string strRegExPattern, 
                             StreamWriter objFileSW, int maxDaysBack)
{
    string[] filenameArray = 
                  Directory.GetFiles(strDirectoryName, filemask, SearchOption.TopDirectoryOnly);

    foreach (string filename in filenameArray)
    {
      Console.WriteLine("Processing file=" + filename);
      string fileContents = File.ReadAllText(filename);

      foreach (Match m in Regex.Matches(fileContents, strRegExPattern))
      {
        //Console.WriteLine("'{0}' found at index {1}.",m.Value, m.Index);
        string showFilename = Path.GetFileName(filename);
        FileInfo fileInfo = new FileInfo(filename);
        TimeSpan daysBack = DateTime.Now.Subtract(fileInfo.LastWriteTime);
        
        if (daysBack.Days < maxDaysBack)
        {

          //Worthless Capture collection! 
          /*
          foreach (Capture capture in m.Captures)
          {
             Console.WriteLine("Index={0}, Value={1}", capture.Index, capture.Value);
          }
          */

          int loopCounter = 0;
          foreach (Group grp in m.Groups)
          {

            loopCounter++;
            if (loopCounter == 2)  // trying to avoid subscript error 
            {
              string PONum = grp.Captures[0].Value;
              Console.WriteLine(loopCounter + " " + showFilename + " " + PONum);
              string outline = prefix + "," +
                                                                filetype + "," + 
                                                                showFilename + "," + 
                                                                fileInfo.LastWriteTime +
                                                                "," + PONum;
              objFileSW.WriteLine(outline);
            }
          }
        }
        else
        {
          Console.WriteLine("Skipping file " + showFilename + " Created=" + 
                                                          fileInfo.CreationTime + 
                                                          " Over " + maxDaysBack + " Days Ago"); 
        }

      }  // end foreach 

  }
} 

</pre>

Uncategorized  

Leave a Reply