How to detect files pending save?

Patricia 5 Reputation points
2023-08-25T05:13:13.4133333+00:00

I'm trying to follow the Sergey commenton this same question, on how to detect a file that has a "pending save state".

Code:

using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.Shell;

namespace Link
{
    public static class ProjectHelpers
    {
        static ProjectHelpers()
        {
            // Rely on caller being on UI thread as shouldn't do it here in the constructor.
#pragma warning disable VSTHRD010 // Invoke single-threaded types on Main thread
            Dte = (DTE)Package.GetGlobalService(typeof(DTE));
#pragma warning restore VSTHRD010 // Invoke single-threaded types on Main thread
            Dte2 = (DTE2)Package.GetGlobalService(typeof(DTE));
        }

        public static DTE Dte { get; }

        public static DTE2 Dte2 { get; }
    }
}

and then i'm calling Dte.Documents as:

try
{
      await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

      // Enumerate through open documents
      foreach (Document doc in ProjectHelpers.Dte.Documents)
      {
         // Check if the document has unsaved changes
         if (!doc.Saved)
         {
            Console.WriteLine($"Unsaved changes in document: {doc.FullName}");
         }
      }
}
catch (Exception ex)
{
      Console.WriteLine(ex.Message);
}

The data necessary to complete this operation is not yet available. (Exception from HRESULT: 0x8000000A)

What i'm missing?

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
5,110 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,916 questions
Visual Studio Extensions
Visual Studio Extensions
Visual Studio: A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.Extensions: A program or program module that adds functionality to or extends the effectiveness of a program.
216 questions
{count} votes

1 answer

Sort by: Most helpful
  1. P a u l 10,731 Reputation points
    2023-08-25T09:05:32.33+00:00

    Rather than using a static ProjectHelpers constructor to initialise your DTE instances, as a test could you make that an ordinary static method & then call that after your package is initialised?

    The error suggests that it might be the initialisation order.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.