Can't read the text file in metro apps?

2019-07-30 22:49发布

问题:

I can read the text file for first time. when i try to read the same text file next time, it quit the function and return null value.

    static string configData = "";
    async public void readtextFile(string folder, string file)
    {
        StorageFolder storageFolder = await Package.Current.InstalledLocation.GetFolderAsync(folder);
        StorageFile storageFile = await storageFolder.GetFileAsync(file);
        configData = await FileIO.ReadTextAsync(storageFile);
    }

Please suggest me, how to resolve this issue..

Thanks SheikAbdullah

回答1:

Don't forget that readtextFile is an asynchronous method. When you call it, it actually returns when it reaches the first await, so at this point configData is not set yet. You should return the value from the method, and await the method:

async public Task<string> readtextFile(string folder, string file)
{
    StorageFolder storageFolder = await Package.Current.InstalledLocation.GetFolderAsync(folder);
    StorageFile storageFile = await storageFolder.GetFileAsync(file);
    string configData = await FileIO.ReadTextAsync(storageFile);
    return configData;
}

...

string configData = await readTextFile(folder, file);

Even if you want to store configData in a field, you still need to await readtextFile before you read the value.