如何从文本文件中正确读取值

时间:2018-07-23 12:08:55

标签: c# json text uwp

我正在一个项目中,值存储在一个文本文件中,每次应用程序启动时都应检索该值。 文本文件非常简单明了:

<connectionStrings>
<add name="TestEntities" connectionString="metadata=res://*/DataAccessObjects.TestModel.csdl|res://*/DataAccessObjects.TestModel.ssdl|res://*/DataAccessObjects.TestModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=Test_dev;initial catalog=Test;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />

我有这个简单的类,带有两个数字值:

{
    "HowManyDayImages": "11",
    "HowManyNightImages": "5",
}

然后我有这段代码来查找受关注的文件并从中读取值并进行设置:

public class ImageConfig
{
    public int HowManyDayImages { get; set; }
    public int HowManyNightImages { get; set; }
}

与此有关,我面临两个问题。首先是这一行“ Encoding.UTF8.GetString(Properties.Resources.imageConf);”我收到这样的错误:当前上下文中不存在“属性”。

The Dynamic folder inside the project

我面临的第二个问题是,我不断收到一条错误消息,指出找不到“动态”。

1 个答案:

答案 0 :(得分:3)

  

如何从文本文件中正确读取值

首先,您需要一个存储json信息的文本文件,然后将其存储在您下次可以访问的指定文件夹中。

创建文本文件

// Create sample file; replace if exists.
Windows.Storage.StorageFolder storageFolder =
    Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile sampleFile =
    await storageFolder.CreateFileAsync("sample.txt",
        Windows.Storage.CreationCollisionOption.ReplaceExisting);

将文本写入文件

Windows.Storage.StorageFolder storageFolder =
    Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile sampleFile =
    await storageFolder.GetFileAsync("sample.txt");

await Windows.Storage.FileIO.WriteTextAsync(sampleFile, "json info");

第二从文本文件中加载文本,然后使用JsonConvert来反序列化文本。

从文件读取

string json = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);

var item = JsonConvert.DeserializeObject<Item>(json);

第三DeserializeObject加载通过上述步骤获得的设置。

var info = item.info;

注意

  

我面临的第二个问题是,我不断收到一条错误消息,指出找不到“动态”。

从屏幕快照(存储在项目目录下的Dynamic文件夹)中,您无法使用LocalFolder来获取它。请使用软件包InstalledLocation

var folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Dyanmic");
相关问题