gpt4 book ai didi

c# - 使用 FileStream 创建文件会返回 InvalidOperationException

转载 作者:行者123 更新时间:2023-11-30 13:55:50 25 4
gpt4 key购买 nike

它在 第 12 行 返回exception

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

如果需要,异常消息中有更多详细信息:

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

谢谢!

最佳答案

考虑这样的事情? :

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

关于c# - 使用 FileStream 创建文件会返回 InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31769505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com