|
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, 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;
}
}
catch (Exception e)
{
logging.Error("Error Processing --> " + e.Message);
logging.Error("************* Stack Trace *******************");
logging.Error(e.StackTrace);
throw new Exception(e.Message);
}
}
}
|
|
|
|
|
Why wouldn't you just put a foreach directory loop around the GetFiles loop?
|
|
|
|
|
 Hi,
I just refactored your code, it goes through your root dir and look for the sub dirs that you wanted and check for the files you wanted. If you want to change the sub dirs or add new sub dirs, you just need to edit the "SubDirNames" array.
private string[] SubDirNames = new string[]
{
"Cancel",
"ED",
"UI",
"RCS"
};
private List<string> GetSubDirectoryPaths(DirectoryInfo rootDir)
{
List<string> subDirs = new List<string>();
foreach (string subDirName in SubDirNames)
{
DirectoryInfo[] dirs = rootDir.GetDirectories(subDirName);
if (dirs.Length > 0)
{
subDirs.Add(dirs[0].FullName);
}
else
{
string path = Path.Combine(rootDir.FullName, subDirName);
Directory.CreateDirectory(path);
logging.Error("The location " + path + " does not exist for documents. ");
}
}
return subDirs;
}
private string[] GetFiles(string subDir)
{
return (from path in Directory.GetFiles(subDir)
let name = Path.GetFileName(path)
where name.EndsWith(".pdf") ||
name.EndsWith(".xlsx") ||
name.EndsWith(".xls")
select path).ToArray();
}
public string addNewPKG()
{
try
{
string packageId = "";
DateTime myDateTime = DateTime.Now.AddMonths(-1);
string fromDate = "_" + myDateTime.ToString("MMM").ToUpper() + " _" + myDateTime.ToString("yyyy");
string rootDirPath = Path.Combine(ConfigurationSettings.AppSettings["tLocation"], fromDate);
DirectoryInfo rootDir = new DirectoryInfo(rootDirPath);
if (!rootDir.Exists)
{
rootDir.Create();
logging.Error("The location " + rootDirPath + " does not exist for documents. ");
return packageId;
}
else
{
List<string> subDirPaths = GetSubDirectoryPaths(rootDir);
foreach (string subDir in subDirPaths)
{
string[] RVWFiles = GetFiles(subDir);
if (RVWFiles.Length > 0)
{
foreach (string RFile in RVWFiles)
{
string orgnizationName = "";
string contactName = "";
string fileNameWithExtension = Path.GetFileName(RFile);
string fileName = Path.GetFileNameWithoutExtension(RFile);
string Original_location = subDir;
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];
}
}
else
{
logging.Info("packageId: " + packageId + " the location " + subDir + " does not contain any documents. ");
return packageId;
}
}
}
}
catch (Exception e)
{
logging.Error("Error Processing --> " + e.Message);
logging.Error("************* Stack Trace *******************");
logging.Error(e.StackTrace);
return packageId;
}
return null;
}
There are few other things, I an not sure about your "PackageId" variable, this is empty at the moment; and why are you returning the packageId when error occurs and returning "null" when success?
Second, don't throw exception on exception, it is pointless, either handle the exception or let the compiler does what it does best.
Third, if i were you, I would move the processing part of the file into a separate method too for better readability.
I hope this helps.
Regards
Jegan
Think! Don't write a line of code unless you absolutely need to.
modified 10-Mar-13 20:22pm.
|
|
|
|
|
Thank you for your answer!
I placed the value for the packageid in the worn locations!
|
|
|
|
|
|
|
|
zebra88 wrote: Can i make this field look like as ..... rather than numbers?
Developed in Access? Or C#? WinForms? What?
If WinForms and a TetxBox, then look into PasswordChar[^]
If not, I have no idea.
modified 11-Mar-13 9:49am.
|
|
|
|
|
The typical way to store a password securely is typically not to store it at all. I know this sounds backwards, but what normally happens is that you hash the password beforehand and you save that hashed version to the database, along with the salt that you used to create the hash. Then, when you want to compare, you retrieve the row and perform the same hash using the salt that you saved to the database.
Now, before you ask, I've given you every keyword in there that you need to do this.
|
|
|
|
|
I am doing one sample project in c#. Its lik billing project. I created combobox column in datagridview. i added items to combobox if i select one item from combobox in one row tat item should not list in next row combo box. Is it possible if yes means suggest me please.
Thanks in advance
|
|
|
|
|
I have develop simple application first I take birthday from user and calculate his lucky number from sum of the values of the birthday
Ex:
'19881205'
How i get the sum of values in this string?
|
|
|
|
|
Use one of the integer methods[^] to parse it into a number and then use the Digital root method[^]. Alternatively extract each character one at a time, and sum the integer values.
Use the best guess
|
|
|
|
|
|
Long winded, but as a demo...
static void SumNumbersinDate()
{
string theDate = "19881205";
char[] dateLetters = theDate.ToCharArray();
int[] dateNumbers = new int[theDate.Length];
int sum = 0;
for (int ind = 0; ind < theDate.Length; ind++)
{
Console.WriteLine("Current Total: " + sum.ToString());
dateNumbers[ind] = int.Parse(dateLetters[ind].ToString());
Console.WriteLine("Adding: " + dateNumbers[ind].ToString());
sum += dateNumbers[ind];
Console.WriteLine("New Total: " + sum.ToString());
}
Console.WriteLine("The sum of the numbers is: " + sum.ToString());
Console.WriteLine("Press any key to close the demo...");
Console.ReadKey(true);
}
|
|
|
|
|
|
Integer.TryParse is often the best solution since it ensures you are parsing an integer and if not, does not throw an error.
|
|
|
|
|
Do you also have to verify that a date is valid?
I'd hazard a guess that maybe you should.
Garbage-In = Garbage-Out
Q. Hey man! have you sorted out the finite soup machine?
A. Why yes, it's celery or tomato.
|
|
|
|
|
Since OP needs this to calculate a "lucky number" I wouldn't worry too much about "garbage".
"I had the right to remain silent, but I didn't have the ability!"
Ron White, Comedian
|
|
|
|
|
|
Don't bump your question, it is bad manners.
|
|
|
|
|
It's also spectacularly stupid when your question is already at the top of the list...
If you get an email telling you that you can catch Swine Flu from tinned pork then just delete it. It's Spam.
|
|
|
|
|
I did wonder if he double submitted, but the I realised the site protects against this and the time-stamp was 10 minutes apart.
[Edit]
I'm back off to bed, I've lost the ability to type.
|
|
|
|
|
You might wanted to enter the text here[^].
|
|
|
|
|
|
This is not a good question - we cannot work out from that little what you are trying to do.
Remember that we can't see your screen, access your HDD, or read your mind.
If you get an email telling you that you can catch Swine Flu from tinned pork then just delete it. It's Spam.
|
|
|
|