简体   繁体   中英

Windows Phone 8.1 - Read Files from Documents folder without using UI

I am running a Windows Phone 8.1 app and I want on startup to get some values from a text file that is stored in "C:\\Data\\Users\\Public\\Documents\\file.txt"

I don't want to open a UI for that, the application should do it without user intervention. The location is outside my app (ie C:\\Data...).

How can I do this?

For example:

Uri uri = new Uri(@"C:\Data\Users\Public\Documents\test.txt");
var f = awaitWindows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);

does not work. It gives an exception: Message = "Value does not fall within the expected range."

You won't be able to access that folder in a windows phone app. Instead store your files in a local folder for your app, then just use a stream reader on it. This is what I use in my app:

// RETURN ROWS IN TEXT FILE AS STRING ARRAY
public static async Task<string[]> getData(string fileName)
{
    var myStream = await (await Package.Current.InstalledLocation.GetFolderAsync("MyFolder")).OpenStreamForReadAsync(fileName);
    using (var streamReader = new StreamReader(myStream))
        return streamReader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
}

Simply get the folder where your file is located using GetFolderFromPathAsync and then get your file from that folder using GetFileAsync . After that you can read all its content using ReadTextAsync method. Hope this helps.

public static async Task<string> ReadFile()
{
  StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(ApplicationData.Current.LocalFolder.Path + "\\" + "YourFolderName");
  StorageFile file = await folder .GetFileAsync("yourfile.txt");
  string text = await Windows.Storage.FileIO.ReadTextAsync(file);
  return text;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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