繁体   English   中英

从文件写入和读取

[英]Write and Read from a file

我一直在关注本教程http://msdn.microsoft.com/zh-cn/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();
            }

        }
    }
}

}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM