There are many threads on the web that speak of reading a text file in a Windows Phone 7 application however most of them target Isolated Storage which is required when you need to manipulate data during execution/runtime. Opposite to that there are scenarios when your application requires various forms of data avaialble as part of the application package itself and deployed on the client device rather than being manipulated during execution of your application.
This post is targeted for such a scenario and shows how to read a text file (that is packaged as part of the contents of the XAP package) in the Windows Phone 7 application. The code is as follows (assumign the file Data.txt is contained in a root folder named Data)
public string ReadFileContents() { //this verse is loaded for the first time so fill it from the text file var ResrouceStream = Application.GetResourceStream(new Uri("/Data/Data.txt", UriKind.Relative)); if (ResrouceStream != null) { Stream myFileStream = ResrouceStream.Stream; if (myFileStream.CanRead) { StreamReader myStreamReader = new StreamReader(myFileStream); //read the content here return myStreamReader.ReadToEnd(); } } return string.Empty; }
Note that the Copy to Output Directory is set to “Do not copy” and Build Action is set to “Content”.
As it may be obvious to the readers, setting Build Action to “Content” makes the XAP package size larger since the text file contents are merged within the XAP package. The folder structure is maintained in the XAP package and can be verified by opening the XAP file in WinZip/Rar)