3
Answers

C# modify a foreach loop

Photo of dc

dc

12y
2.1k
1
I have a question about how to modify the C# 2008 desktop  foreach (String RFile in RFiles) block of code and/or the code that is surrounding this block of code. The code I am referring
  to is listed below.  Originally the code was setup to select files in a specific file directory. Now the requirements have changed where I need to loop through
  4 subfoler directories that are at the same folder level. The 4 folder levels will be: 1. C:\customer\Mon_year\Cancel, 2. C:\customer\Mon_year\ED, 3. C:\customer\Mon_year\UI, and  4. C:\customer\Mon_year\UI.

  Right now these are the only folders that will be setup at this level in the directory structure. However I can see how there can potentially be other directories created at this
  level in the future.

  I would like to be able to resue the foreach (String RFile in RFiles) block without repeating the 4 times.

  Thus can you show me how to modify this code and/or tell me how I can change this code? 

  public String addNewPKG()
  {
  {
  try
  {
  String packageId = "";
  int intReviewFileCount = 0;
  string Format_year = DateTime.Now.AddMonths(-1).ToString("yyyy");
  string strMonth = DateTime.Now.AddMonths(-1).ToString("MMMM").ToUpper();
  string Format_Date = "_" + strMonth.Substring(0, 3) + "_" + Format_year;
  String filesaveLocation = null;
  filesaveLocation = Path.Combine(ConfigurationSettings.AppSettings["tLocation"], Format_Date);
  string strCancel = "Cancel";
  string strED = "ED";
  string strUI = "UI";
  string strRCS = "RCS";
  //string strsubfilesaveLocation = Path.Combine(filesaveLocation,strCancel);
  //string strsubfilesaveLocation = Path.Combine(filesaveLocation, strED);
  //string strsubfilesaveLocation = Path.Combine(filesaveLocation, strUI);
  string strsubfilesaveLocation = Path.Combine(filesaveLocation, strRCS);
  if (!Directory.Exists(strsubfilesaveLocation))
  {
  System.IO.Directory.CreateDirectory(strsubfilesaveLocation);
  logging.Error("The location " + strsubfilesaveLocation + " does not exist for documents. ");
  return packageId;
  }

  else
  {
  string[] RVWFiles = (from path in Directory.GetFiles(strsubfilesaveLocation)
  let name = Path.GetFileName(path)
  where name.EndsWith(".pdf") ||
  name.EndsWith(".xlsx") ||
  name.EndsWith(".xls")
  select path).ToArray();
  if (RVWFiles.Length == 0)
  {
  logging.Info("packageId: " + packageId + " the location " + strsubfilesaveLocation + " does not contain any documents. ");
  return packageId;
  }
  foreach (String RFile in RFiles)
 
  {
  string orgnizationName = "";
  string contactName = "";
  string fileNameWithExtension = Path.GetFileName(RFile);
  string fileName = Path.GetFileNameWithoutExtension(RFile);
  string Original_location = filesaveLocation;

  string[] names = fileName.Split('_');
  orgnizationName = names[0].TrimEnd();
  contactName = names[1].TrimStart();
 

  string strOrgnizationName = orgnizationName;
 
  string[] items = contactName.TrimEnd().Split(' ');
  string surname = items[items.Length - 1];
  --here does the processing that is required--
 
  return null;
  } //closing bracket for  foreach (String RFile in RFiles)
  }

  catch (Exception e)
  {
  logging.Error("Error Processing --> " + e.Message);
  logging.Error("************* Stack Trace *******************");
  logging.Error(e.StackTrace);
  throw new Exception(e.Message);
  }
  }
 
  }

Answers (3)

0
Photo of Vulpes
NA 96k 2.6m 12y
1. Noted.

2. Well, you have a number of conditional return statements within the method. If you tried to deal with all 4 sub-folders at once within the method, then it would return as soon as the condition was met for just one of the sub-folders which may not be what you want.

It seemed to me that it would therefore be advisable to leave the method to deal with a single sub-folder and to call it 4 times with each of the sub-folders.

3. That code would be need to be put wherever you are currently calling the addNewPKG method. If this is in several places, then it might be a good idea to put it into its own routine and then call that routine. However, if you're only calling it once, I don't think I'd bother with a separate routine.  
0
Photo of dc
NA 663 0 12y
I have the following additional items to mention:
1. The processing that occurs within the loop calls a web service to obtain the package id value. That is why the is within this loop.
2. Can you explain to me what you mean by the following statement:
"However, it looks to me like you should be doing this from the code which calls the addNewPKG method rather than from within the method itself, because you may need to return prematurely if there's an error for a particular sub-folder. You'd then need to pass the sub-folder as an argument to that method:"

3. Where  would you place the following code, in its own routine:
List<string>  strSubFolders = new List<string>{"Cancel", "ED", "UI", "RCS"};
foreach (string strSubFolder in strSubFolders)
{
    string packageId = addNewPKG(strSubfolder);
    // do something with packageId
}

// ...

Thanks!
0
Photo of Vulpes
NA 96k 2.6m 12y
Well, essentially you need to put the four sub-folders into a List<string> which you can add to later, if needed.

You can then iterate though the list and perform the steps you're currently doing for a single folder on each sub-folder.

However, it looks to me like you should be doing this from the code which calls the addNewPKG method rather than from within the method itself, because you may need to return prematurely if there's an error for a particular sub-folder. You'd then need to pass the sub-folder as an argument to that method:

List<string>  strSubFolders = new List<string>{"Cancel", "ED", "UI", "RCS"};
foreach (string strSubFolder in strSubFolders)
{
    string packageId = addNewPKG(strSubfolder);
    // do something with packageId
}

// ...

public String addNewPKG(String strSubFolder)
    {
      try
      {
         String packageId = "";
         int intReviewFileCount = 0;
         string Format_year = DateTime.Now.AddMonths(-1).ToString("yyyy");
         string strMonth = DateTime.Now.AddMonths(-1).ToString("MMMM").ToUpper();
         string Format_Date = "_" + strMonth.Substring(0, 3) + "_" + Format_year;
         String filesaveLocation = null;
         filesaveLocation = Path.Combine(ConfigurationSettings.AppSettings["tLocation"], Format_Date);         
         string strsubfilesaveLocation = Path.Combine(filesaveLocation, strSubFolder));
 
         if (!Directory.Exists(strsubfilesaveLocation))
         { 
               System.IO.Directory.CreateDirectory(strsubfilesaveLocation);
               logging.Error("The location " + strsubfilesaveLocation + " does not exist for documents. ");
               return packageId; 
         }
         // etc
     
}