0

几周前,我在此主题中提出了类似的问题Write and Read from a file并且我的问题得到了回答,但是现在我正在尝试读取文件并使用 if 函数,但目前我只能从文本块中读取通过按一个按钮来读取文件并传输到 txtblock,所以我想知道如何能够不使用这种方式进行读取。此刻在这里。

 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();
            }

        }
    }


    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        await ReadFile();

        if (textBlock1.Text == "test")
            star2.Visibility = Visibility.Visible;
    }
4

2 回答 2

1

花了一秒钟弄清楚我认为你的意思。

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

尝试这个:

        string readtxt;
        using (StreamReader streamReader = new StreamReader(file))
        {
            readtxt = streamReader.ReadToEnd();
        }

现在您将拥有一个字符串变量“readtxt”,它可以以任何字符串类型的所有方式工作并包含文件的内容。

于 2013-10-07T00:43:35.160 回答
1
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");

        string = readtext
        // Read the data.
        using (StreamReader streamReader = new StreamReader(file))
        {
            readtext = streamReader.ReadToEnd();
        }
        if (readtxt == "x")
                x do something
    }
}

Thanks to @Dweeberly for helping

于 2013-10-07T03:14:28.580 回答