GetFiles: Wrong result
I'm using the following code in a recursive call:
var files = di.GetFiles("*.jpg");
di is a DirectoryInfo that is passed in to the function. Assume a file tiger.jpg in the root of some drive k. Occasionally, the result is not k:\tiger.jpg but k:\iger.jpg. I have no idea why or how. Has anyone ever had the same behavior?
Edit 1: It seems to occur even with directory names, because the recursive function does not list images in a subdirectory. I think it is mostly FAT ( because it usually reads from media such as SD card or USB sticks, sometimes from a DVD or CD ).
The fullname of each returned FileInfo object is signalled u开发者_如何学Csing an event. The recipient creates a new object that takes the path as an argument to the constructor. The constructor then calls a method that uses the path for getting information about the jpeg files:
FileStream fs = File.Open ( this.Path, FileMode.Open );
Image img = Image.FromStream ( fs, false, false );
This is where the exception occurs. As I get the files from a call to a framework component, I do not explicitly check again if they exist - I can build this into the system, but that does not solve my problem.
One thing I forgot: This does not happen on our test systems, but on a system round the globe :(
Could be the wrong straw, but have you tried escaping the \
.
In your example of k:\tiger.jpg
C# will read the \t
as a tab. This shouldn't really happen, but I have seen it occur. Try writing it so that all backslashes are replaced with \\
Antivirus can sometimes come into play here. If you have one process generating the file and one process that is using it, you may have a race condition.
Rather than checking for the files existence, call the File.Open and then try/catch for an IOException
. You will need to then check what's happening when you hit the exception.
You can never assume that a file exists.
As for why you are losing a letter of the file name, how are you generating this.Path
?
In this particular case, it seems it was a specific combination of hardware that triggered some weird behavior. The Win32 API brought up correct results while the .NET API returned wrong results.
This wasn't reproducible on all installations. The only obvious difference were localization settings, but even changing them on a functional didn't helped us coming up with a repro on one of our local machines. As a new hardware revision will be rolled out there are no further investigations.
If you're sure you have covered all proposals from the other answers and have the very same problem, you might want to contact the OS vendor.
精彩评论