Creating a file with FileStream returns an InvalidOperationException

血红的双手。 提交于 2019-12-10 18:20:47

问题


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!


回答1:


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);
        }
    });
}


来源:https://stackoverflow.com/questions/31769505/creating-a-file-with-filestream-returns-an-invalidoperationexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!