Operation is not valid due to the current state of the object.

Peter Reilly 20 Reputation points
2025-03-20T13:41:01.8133333+00:00

Directly copied from Microsoft Learn

Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

Results in this error:

System.InvalidOperationException: 'Operation is not valid due to the current state of the object.'

VS2022, Windows 11, C# 11, .Net 8

I have review all the previous answers to this problem from varios sources, but nothing applies to my situation.

Developer technologies | C#
{count} votes

Accepted answer
  1. Anonymous
    2025-03-24T11:25:31.1166667+00:00

    Hi @Peter Reilly , Welcome to Microsoft Q&A,

    Windows.Storage.ApplicationData is not suitable for use in Winforms.

    If you just want to read and configure the application at startup, you can use xml or Properties.Settings (.NET built-in function), both of which are good choices.

    In VS Solution Explorer, find PropertiesSettings.settings, add keys such as MaxGridSize, MinGridSize, and set default values.

    You can call it directly in the program like this:

    MaxGridSize = Properties.Settings.Default.MaxGridSize;
    Properties.Settings.Default.MaxGridSize = 100;
    Properties.Settings.Default.Save();
    
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

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.