Reputation: 77
Currently I am writing the windows service to process massive xml files and save info from xml file to database. There are 3 machines running the same services that point to the same share location. I always got exception that File Not Found during the process and don't know how to solve this problems. I tried to get all file from the directory and rename those files based on the machine name and allow each machine to process it own set of files but still suffer from File Not Found exception. Could anyone show me the proper way to deal with this.
Thank you.
Code
if (Directory.Exists(folder))
{
string pattern = ".xml";
string machineName = System.Environment.MachineName;
string[] files = Directory.GetFiles(folder, pattern, SearchOption.AllDirectories);
newExt = string.Format("{0}.{1}", machineName, newExt);
for (int i = 0; i < files.Length; i++)
{
if (files[i].Contains(machineName))
{
//replace this new extension
files[i].Replace(machineName + ".", "");
}
else
{
files[i] = ChangeExtension(files[i], newExt, true);
}
}
IEnumerable<string> sortedFiles = files.Where(f => !string.IsNullOrEmpty(f) && f.Contains(machineName))
.OrderBy(f => f, Sorter);
}
Upvotes: 0
Views: 329
Reputation: 2546
As Eric J mentioned, you could simply ignore the errors:
if (Directory.Exists(folder))
{
string pattern = ".xml";
string machineName = System.Environment.MachineName;
string[] files = Directory.GetFiles(folder, pattern, SearchOption.AllDirectories);
newExt = string.Format("{0}.{1}", machineName, newExt);
for (int i = 0; i < files.Length; i++)
{
try
{
if (files[i].Contains(machineName))
{
//replace this new extension
files[i].Replace(machineName + ".", "");
}
else
{
files[i] = ChangeExtension(files[i], newExt, true);
}
catch(FileNotFoundException ex)
{
}
}
IEnumerable<string> sortedFiles = files.Where(f => !string.IsNullOrEmpty(f) && f.Contains(machineName))
.OrderBy(f => f, Sorter);
}
Upvotes: 0
Reputation: 18534
Could you, please, explain with what names files appear in the directory?
P.S.: surely, if you feel, that I failed to catch the issue, could you, please, provide some more accurate info.
Upvotes: 0
Reputation: 150108
It's hard to see what's happening without looking at your code, but I'll speculate that the three individual servers get a directory listing, select a file from that listing to work on, and in the mean time a different server has renamed the file because the other server decided to start working on the file.
If this happens infrequently, you can ignore the Exception (assuming my explanation is correct). If this happens frequently you will need to explain in more detail what you are doing.
You can minimize contention for the same file by having each server sort the file listing in a different way (e.g. one A-Z, the second Z-A, the third L-Z, A-J, ...) and then pick the top one in the sort order to work on.
Upvotes: 1