简体   繁体   中英

Why does the Name Property of FileInfo object start with “~$”?

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

~$ indicates that the file is a temporary file used by Microsoft Office. See here for additional information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM