从文件写入和读取

时间:2013-09-26 12:31:00

标签: c# windows-phone-8

我一直在关注本教程http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj681698%28v=vs.105%29.aspx

到目前为止我正在搜索,但唯一的问题是,当我关闭并再次打开应用程序时,文件和文本不再保存,所以我希望文件永远保存文本。

我希望将其保存在http://gyazo.com/82e838cd2385cea7021647a8d39f49a8.png/level/batlevel.txt。因此,当我再次打开应用程序时,那里写的文本就会在那里

    private async void btnWrite_Click(object sender, RoutedEventArgs e)
    {
        await WriteToFile();

        // Update UI.
        this.btnWrite.IsEnabled = false;
        this.btnRead.IsEnabled = true;
    }

    private async Task WriteToFile()
    {
        // Get the text data from the textbox. 
        byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(this.textBox1.Text.ToCharArray());

        // Get the local folder.
        StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;

        // Create a new folder name DataFolder.
        var dataFolder = await local.CreateFolderAsync("level",
            CreationCollisionOption.OpenIfExists);

        // Create a new file named DataFile.txt.
        var file = await dataFolder.CreateFileAsync("level.txt",
        CreationCollisionOption.ReplaceExisting);

        // Write the data from the textbox.
        using (var s = await file.OpenStreamForWriteAsync())
        {
            s.Write(fileBytes, 0, fileBytes.Length);
        }
    }
    private async void btnRead_Click(object sender, RoutedEventArgs e)
    {
        await ReadFile();

        // Update UI.
        this.btnWrite.IsEnabled = true;
        this.btnRead.IsEnabled = false;
    }

    private async Task ReadFile()
    {
        // Get the local folder.
        StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;

        if (local != null)
        {
            // Get the DataFolder folder.
            var dataFolder = await local.GetFolderAsync("level");

            // Get the file.
            var file = await dataFolder.OpenStreamForReadAsync("level.txt");

            // Read the data.
            using (StreamReader streamReader = new StreamReader(file))
            {
                this.textBlock1.Text = streamReader.ReadToEnd();
            }

        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

我认为您应该使用OpenIfExists选项而不是ReplaceExisting打开 level.txt 文件:

// Create a new file named DataFile.txt.
var file = await dataFolder.CreateFileAsync( "level.txt", CreationCollisionOption.OpenIfExists );