我使用 Json 文件来存储与应用程序相关的对象。 读取有效,但我对写入文件感到困惑。
private static void WriteFileContentsAsync(string content)
{
var local = IsolatedStorageFile.GetUserStoreForApplication(); //(new Uri("Common/DataModel/EventsData.json", UriKind.Relative));
var eventsFile = local.OpenFile("Common/DataModel/EventsData.json", FileMode.Open);
using (StreamWriter writer = new StreamWriter(eventsFile))
{
writer.WriteAsync(content);
}
}
我无法打开位于我的项目中的文件 -> Common/DataModel/EventsData.json 异常告诉我该操作是不允许的。
这是我从同一个文件中读取的方式:
private static string ReadFileContents()
{
var ResrouceStream = Application.GetResourceStream(new Uri("Common/DataModel/EventsData.json", UriKind.Relative));
if (ResrouceStream != null)
{
using (Stream myFileStream = ResrouceStream.Stream)
{
if (myFileStream.CanRead)
{
StreamReader myStreamReader = new StreamReader(myFileStream);
return myStreamReader.ReadToEnd();
}
}
}
return string.Empty;
}
但是 myFileStream.CanWrite
是错误的。
什么是正确的选择?
编辑
我尝试了另一种方法,但它应该写入的文件没有改变,也没有发生错误:
private static void WriteFileContentsAsync(string content)
{
FileStream fs = new FileStream("Common/DataModel/EventsData.json",FileMode.Open,FileAccess.Write);
if (fs.CanWrite)
{
using (StreamWriter writer = new StreamWriter(fs))
{
writer.WriteAsync(content);
}
}
}
最佳答案
你不能只使用:
IsolatedStorageFile isoFile;
isoFile = IsolatedStorageFile.GetUserStoreForApplication();
// Open or create a writable file.
IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream("Common/DataModel/EventsData.json",
FileMode.OpenOrCreate,
FileAccess.Write,
isoFile);
StreamWriter writer = new StreamWriter(isoStream);
关于c# - 写入项目文件夹中的文件 - 不允许操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23563420/