Search code examples
c#serializationfilestream

Creating a file with FileStream returns an InvalidOperationException


It returns the exception specifically at line 12.

    public void saveToXML()
    {
        URL newURL = new URL();
        newURL.type = type;
        newURL.name = name;
        newURL.info = info;
        newURL.url = url;
        newURL.isProtected = isProtected;
        newURL.amountOfClicks = amountOfClicks;
        XmlSerializer xml = new XmlSerializer(typeof(URL));
        string directory = @"C:\Users\PC-User\Documents\Link" + newURL.name + ".xml";
        using (var file = File.Create(directory))
        {
            xml.Serialize(file, url);
        }
    }

More details in exception message if needed:

Synchronous operations should not be performed on the UI thread. Consider wrapping this method in Task.Run.

Thanks!


Solution

  • Consider something like this? :

    public async Task saveToXml(){
        string directory = @"C:\Users\PC-User\Documents\Link" + newURL.name + ".xml";
        await Task.Run(()=>
        {
            Task.Yield();
            using (var file = File.Create(directory))
            {
                xml.Serialize(file, url);
            }
        });
    }