如何将文件的每一行加载到不同的文本框中

时间:2017-06-15 16:54:59

标签: c# uwp windows-10 visual-studio-2017

我的应用需要一些帮助。 我是C#和UWP编程的初学者。 我有3个文本框,我在文本文件中保存每行的数据。 我使用ApplicationData.Current.LocalFolder来完成它。

但是如何将每一行加载回文本框?

我已经为每个文本框创建了一个文件,但是当我需要在应用程序中使用其他一些内容再次执行此操作时,会有很多文件。

希望这是可以理解的!

以下是我为保存而做的代码。

    private async void OpretBilFlyoutButton_Click(object sender, RoutedEventArgs e)
    {
        string filenameBilmarke = "BilMarke.txt";
        string bilMarke = BilMarke.Text;
        string bilModel = BilModel.Text;
        string kmTaller = KmTaller.Text;

            StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            StorageFile fileBilMarke = await localFolder.CreateFileAsync(filenameBilmarke, CreationCollisionOption.ReplaceExisting);
            await FileIO.WriteTextAsync(fileBilMarke, bilMarke + "\r\n" + bilModel + "\r\n" + kmTaller);
   }

1 个答案:

答案 0 :(得分:2)

我就是这样做的。

首先从Nuget安装Json.Net

然后使用要保存的数据创建基类。

public class MyData
{
    public string BilMarke { get; set; }
    public string BilModel { get; set; }
    public string KmTaller { get; set; }
}

要保存数据,您需要将方法更改为以下。

private async void OpretBilFlyoutButton_Click(object sender, RoutedEventArgs e)
{
    string filenameBilmarke = "BilMarke.txt";

    MyData data = new MyData();
    data.BilMarke = BilMarke.Text;
    data.BilModel = BilModel.Text;
    data.KmTaller = KmTaller.Text;

    string finaldata = JsonConvert.SerializeObject(data);

    StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
    StorageFile fileBilMarke = await localFolder.CreateFileAsync(filenameBilmarke, CreationCollisionOption.ReplaceExisting);
    await FileIO.WriteTextAsync(fileBilMarke, finaldata);
}

如果您注意到我将对象MyData序列化为Json并直接保存它。

现在要检索,您只需从文本文件中反序列化内容

MyData textdata = JsonConvert.DeserializeObject<MyData>(finaldata);

您可以将其分配回文本框,如下所示。

BilMarke.Text = textdata.BilMarke;
BilModel.Text = textdata.BilModel;
KmTaller.Text = textdata.KmTaller;

祝你好运。