So I'm writing some code that is going through a directory of .xlsx
files and picking the file that was created last. It's a simple task, but there is something a bit strange happening with the Name
property of a particular FileInfo
object and potentially there are more cases of this occurring.
Here is my code:
DirectoryInfo di = new DirectoryInfo(FolderPath);
FileInfo[] FileArray = di.GetFiles("*.xlsx", SearchOption.AllDirectories);
if (FileArray.Count() != 0)
{
DateTime latestDate = DateTime.MinValue;
string FileName = String.Empty;
foreach (FileInfo File in FileArray)
{
if (File.CreationTime > latestDate)
{
latestDate = File.CreationTime;
FileName = File.FullName;
}
}
}
The FileName
is important because I use it to query the latest file for information and display it. However, the Name
property of a particular .xlsx file (potentially more) is appearing like this ~$File.xlsx
when in fact the file name is really File.xlsx
. This causes the FullName
property to contain these characters as well.
Is there any way to fix this? What triggers this?
Opening an xlsx file results in Excel creating a hidden file with the same name preceded by "~$". So if one of these Excel files are open at the time you retrieve the content of the directory, you will also get the temp file.
Add a filter that excludes hidden files and your issue is fixed.
Example:
FileAttributes attributes = File.GetAttributes(path);
if((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
{
// Hidden file, just skip it
}
From http://msdn.microsoft.com/en-us/library/system.io.file.getattributes.aspx