简体   繁体   中英

How-To: Stop adding files to “Recent files” in Quick Access when opening/saving files with Microsoft.Office.Interop

When opening and saving Word/Excel documents using the following code, the files that are opened and saved are being added to the Recent Files of Windows File Explorer (see screenshot). The code itself works fine for my purposes; I've only copied a small portion with surround relevant code. However, I am having difficulties in stopping this undesired behavior and searching the internet only seems to give me results on how to keep the files from showing up in the "Recent Files" list of the office applications themselves, not Windows File Explorer.

I am running this code on directories that contain in the upper thousands, some even break into 5 digit counts, of Office files in the old non-xml format. When .Open() is called, the original file shows up in the list and when .SaveAs() / .SaveAs2() is called the new file shows up in the list. This happens in real-time as I step through the code and it causes the CPU usage spike from the explorer.exe process. The act of opening and re-saving the old format office files happens rather quickly, and I suspect this causes a large CPU usage load due to explorer.exe constant processing the recent files. Other symptoms that I think are related is that the cursor constantly has the spin-wheel under it when the code is running and the whole OS GUI seems to become somewhat unresponsive.

To be clear, I believe that a proactive solution which keeps Windows from adding files to the list will be the best path to take, rather than a retroactive solution which only does cleanup of the list after the fact.

using WORD = Microsoft.Office.Interop.Word;
using EXCEL = Microsoft.Office.Interop.Excel;

//==============================================================================


try
{
    if (newFileExt == FileExt.NEW_Word)
    {
        //open the doc
        var document = WordApp.Documents.Open(FileName: fdesc.FileInfo.FullName, ConfirmConversions: false, ReadOnly: true, AddToRecentFiles: false, Visible: false);

        //save the doc
        document.SaveAs2(FileName: newname, FileFormat: WORD.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: WORD.WdCompatibilityMode.wdCurrent, AddToRecentFiles: false);

        // close the doc
        document.Close(WORD.WdSaveOptions.wdDoNotSaveChanges);
    }
    else if (newFileExt == FileExt.NEW_Excel)
    {
        // open the workbook
        /// https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel.workbooks.open?view=excel-pia#Microsoft_Office_Interop_Excel_Workbooks_Open_System_String_System_Object_System_Object_System_Object_System_Object_System_Object_System_Object_System_Object_System_Object_System_Object_System_Object_System_Object_System_Object_System_Object_System_Object_
        EXCEL.Workbook workbook = ExcelApp.Workbooks.Open(Filename: fdesc.FileInfo.FullName, ReadOnly: true, IgnoreReadOnlyRecommended: true, AddToMru: false);

        // save the doc
        /// https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel._workbook.saveas?view=excel-pia

        if (workbook.HasVBProject)
        {
            FileInfo newFile = new FileInfo(newname);
            newname = newFile.DirectoryName + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(newFile.Name) + FileExt.NEW_Excel_Macro;
            UpateNewFileNameConsole(new FileInfo(newname));
            workbook.SaveAs(Filename: newname, FileFormat: EXCEL.XlFileFormat.xlOpenXMLWorkbookMacroEnabled, ReadOnlyRecommended: false, AddToMru: false);
        }
        else
        {
            workbook.SaveAs(Filename: newname, FileFormat: EXCEL.XlFileFormat.xlOpenXMLWorkbook, ReadOnlyRecommended: false, AddToMru: false);
        }


        // close the Workbook
        workbook.Close(SaveChanges: false);
    }
    else { throw new Exception("unkown File in conversion"); }

    //move the old file
    File.Move(fdesc.FileInfo.FullName, moveDir.FullName + Path.DirectorySeparatorChar + fdesc.FileInfo.Name);

}
catch (Exception ex)
{
    Debug.WriteLine(ex.Message);
}


//==============================================================================


public static class FileExt
{
    public const string OLD_Word = ".doc";
    public const string NEW_Word = ".docx";
    public const string OLD_Excel = ".xls";
    public const string NEW_Excel = ".xlsx";
    public const string NEW_Excel_Macro = ".xlsm";
    public const string RichTextFormat = ".rtf";
    public const string OldFormatDir = "!old_format";
    }
}

Screenshot of Windows File Explorer after running the code for a bit: 在此处输入图片说明

This may vary slightly depending on the client Operating System version.

To clear File Explorer history in Windows 10 manually open the Registry Editor app. Go to the following Registry key: HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer

Delete the subkey named TypedPaths:

在此处输入图片说明

Open File Explorer, go to the folder %APPDATA%\\Microsoft\\Windows\\Recent\\ and delete all files and folders you see.


Although the history folder is hidden you can still fetch the files you created and delete them programmatically, eg:

string[] recentFiles = System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.History), "*", SearchOption.AllDirectories);

foreach (var file in recentFiles)
{
   System.IO.File.Delete(file);
}

To delete the registry key using code:

string keyName = @"Software\Microsoft\Windows\CurrentVersion\Explorer";
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))
{
    if (key == null)
    {
        // Key doesn't exist. Do whatever you want to handle this case
    }
    else
    {
        key.DeleteValue("TypedPaths");
    }
}

Make a backup of your registry before trying this.

I am facing poor run-time performance due to CPU spikes from explorer.exe when the file entries are added to the Recent Files list.

The act of opening and re-saving the old format office files happens rather quickly, and I suspect this causes a large CPU usage load due to explorer.exe constant processing the recent files. Other symptoms that I think are related is that the cursor constantly has the spin-wheel under it when the code is running and the whole OS GUI seems to become somewhat unresponsive.

Can you first check these common causes - close background processes, in Device Mgr check the IO driver is OK and temporarily disable anti-virus:

  • Too many background processes
  • Driver
  • Anti-virus
  • Malware
  • WmiPrvSE.exe

  1. Downloaded Microsoft's Process Explorer to see what's causing the CPU spikes. See here the high CPU consuming threads, it's this Audioses.DLL+0x1141b0. Can you show/tell me what DLL is taking up the highest CPU when you perform the operation? If its Explorer.EXE not Audioses.DLL consuming the CPU goto step 2 for your solution. If it's something else we may need a PerfCounter trace.

    在此处输入图片说明

  2. Run System File Checker (SFC) scan on the computer to scan for corrupt system files and replace them: http://support.microsoft.com/kb/929833

    "I can't believe that a broken icon would cause explorer.exe to go into a loop, eating up all of the CPU it can."

    and ..

    "I had an exe with an corrupted icon on my desktop, moving it into a folder solved the problem"

  3. If the issue persists create a new user account, login as that user and check if the problem goes away, then you know your profile is corrupt.

  4. Throw better hardware at the problem: Hardware is Cheap, Programmers are Expensive

Ref's:
https://www.techspot.com/community/topics/explorer-exe-high-cpu-usage-probably-not-malware.240788/
https://answers.microsoft.com/en-us/windows/forum/all/explorerexe-high-cpu-usage-tried-everything-i-can/28cf8431-f9db-4169-9237-8e6521ef4c1c
https://linustechtips.com/main/topic/939842-solvedexplorerexe0xa8150-high-cpu-usage/

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