使用FileStream创建文件将返回InvalidOperationException [英] Creating a file with FileStream returns an InvalidOperationException
本文介绍了使用FileStream创建文件将返回InvalidOperationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
它专门在line 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);
}
}
如有必要,请在异常消息中提供更多详细信息:
More details in exception message if needed:
不应在UI线程上执行同步操作.考虑将此方法包装在Task.Run中.
Synchronous operations should not be performed on the UI thread. Consider wrapping this method in Task.Run.
谢谢!
推荐答案
考虑这样的事情吗? :
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);
}
});
}
这篇关于使用FileStream创建文件将返回InvalidOperationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文