c# - 写入项目文件夹中的文件 - 不允许操作

标签 c# json windows-phone-8 isolatedstorage

我使用 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/

相关文章:

c# - 确定 IIS 请求的响应时间

c# - 检索注册提供商的 ETW 提供商 list

c# - F# 内联如何工作?

javascript - javascript中相同对象名称的总和

python - 搜索 JSON,返回 JSON 结构中的字符串

c# - 什么可能导致此内存问题?

c# - 如何使用 ASP.NET MVC5 将 ErrorCode 转换为字符串?

ios - 如何快速解析这个json?

c# - 将 async/await 与 void 方法一起使用

CSS 在 IE11 中旋转图像/图标(微调器)