Data Structures on the Windows Phone 7: Reading & Writing Isolated Storage

 

How do you put data into isolated storage, how do you read data that is in isolated storage? 

You’re right, I have been a big tease around the phone and lists and reading/writing to isolated storage. 

In a later example, I will cover the use off lists into and out of isolated storage. 

IsolatedStorageFile

To save or retrieve files you use the IsolatedStorageFile class.  As we have seen in the previous blog,

I used the Windows 7 approach,  In this blog I show  the code for the Phone 7.  It has been checked that it works in the emulator, to make this work, you add code to the Initialize Method and the Draw Method.  This uses the default Windows Phone Emulator Code, it works as written, to enlarge the font, make the changes to the spritefont1.sprintfont file you added so that you added to draw the fonts for the message.  This is a very simple app,

After opening the Windows Phone XNA Application, add a SprintFont file to the Content, like the following:

image

First: Add the references to your program so that you can perform the isolated storage.

To the using section at the top of the class add:

  •  
    • using System.IO;
    • using System.IO.IsolatedStorage;

 

 using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;
using System.IO;
using System.IO.IsolatedStorage;

Second: At the top of the class add the Spritefont variable and the Vector2 variable to display the Fonts:

     public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        SpriteFont Font1;
        Vector2 FontPos;

Third: To the Initialize method, add the following code:

        protected override void Initialize()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            Font1 = Content.Load<SpriteFont>("SpriteFont1");                        
            FontPos = new Vector2(graphics.GraphicsDevice.Viewport.Width / 2,
                graphics.GraphicsDevice.Viewport.Height / 2);
            /***************************************************************************
             ********************* ISOLATED STORAGE RELATED CODE ***********************/
            /*****************Obtain the virtual store for application*****************/
            IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
            
            /*****************Create a new folder and call it "ImageFolder"************/
            myStore.CreateDirectory("ImageFolder");

            /**********   Create a new file and assign a StreamWriter ******************
                ********   to the store and this new file (myFile.txt)   ******************
                ********   Also take the text contents from the txtWrite ******************
                ********   control and write it to myFile.txt             ******************/

            StreamWriter writeFile = new 
                        StreamWriter(new IsolatedStorageFileStream("ImageFolder\\myFile.txt", 
                                    FileMode.OpenOrCreate, myStore));
            
            writeFile.WriteLine("Happy New Year");
            writeFile.Close();
            /******************** END OF THE ISOLATED STORAGE RELATED CODE **************
             *****************************************************************************/

            base.Initialize();
        }

Now, the Draw Method, make these changes:

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            /*****************************************************************
             *******    Start of reading data out of IsolatedStorageFile    **
             *******    Obtain a virtual store for application              */
            IsolatedStorageFile myStore = 
                    IsolatedStorageFile.GetUserStoreForApplication();
            //The following code will open and read the contents of myFile.txt
            StreamReader readFile = null;
                readFile = new StreamReader(new 
                                            IsolatedStorageFileStream(
                                            "ImageFolder\\myFile.txt", 
                                             FileMode.Open, myStore
                                             )
                                             );
                string fileText = readFile.ReadLine();                                
                readFile.Close();
            /********   End of code to reading data out of IsolatedStorageFile **
             ********************************************************************/

            /**************************************************************
              ****************** Code added to print out to the  ************
              ******************* phone screen "Happy New Year"  ************
              ***************************************************************/
             spriteBatch.Begin();             
                Vector2 FontOrigin = Font1.MeasureString(fileText) / 2;
                // Draw/Write/Print the string
                spriteBatch.DrawString(Font1, fileText, FontPos, Color.OrangeRed,
                                0, FontOrigin, 1.0f, SpriteEffects.None, 0.5f);
                spriteBatch.End();
                /*****************  End of the Code to print out to the ******
                 *****************   phone screen "Happy New Year" ************/

            base.Draw(gameTime);
        }

Finally run your code and you have successfully wrote and read from isolated storage!

image

Now a few words for the crawlers, this is a test of what happens when I put the Technorati Tags/words on a page with a short phrase associated with them.  The first word in each cell is the tag followed by a short phrase.  I will then pull it off the page on Monday and examine the traffic flow.  I will share this information with you the reader. 

Input for Games
android unlike Windows Phone 7 it lacks MS Word
apple leads to use of one button mice
animation, free tools and other stuff
amazon women use amazon.com
art is good for the soul
alaska is a state
at&t is a phone company
against the spread of the flu
america the beautiful
adventure in game design
airports are crowded
audio and video
alcohol can kill you, but so can to much candy
austerity for governments good
animated sprites
apps on Windows Phone 7
autism is depressing for families
advice column for everyone
air travel is faster than traveling by car
advertising is a way to make money
android 2.2 is not as good as Windows Phone 7, it lacks Excel
book a table
bob on books is a critical read
business is improving
black friday shopping
barack obama is a good president
blogging is fun
barnes  & noble bookstores has a free coupon
blackberry is a phone and could be blackberry jam
beatles made good music, but are Beatles different than bugs?
bristol palin really?
blogs are a way to tell a story
*** cancer is not a good for anyone
banks are not paying much in interest
brian solis I have no idea who this is
brand is something people do to cattle
christmas is a holiday
children are funny
cd is short for certificate of deposit
comedy is funny
celebrity is something one can achieve
crime is bad
culture of bacteria
cyber monday is it real?
cancer, really bad
cartoon like Yogi Bear are funny
cooking is something that saves money
civil rights are good for everyone
childfree and happy to be
credit is something I give to Kenny Spade
cnn is a poorly viewed news network, not sure why
china is a country and delicate dishware
classic jazz is interesting
comcast is a cable company
cell phones are good to have
colombia is a country and an university
chrome is a metal
concert of ideas!
charity for homeless people
childless by choice and happy
computer are on or off
cell phone do you really want one
calories are good till you get too many
college football is fun to watch
dvd are kind of going out of style
dream act what are the polls saying
diet if you are fat
documentary of small people
dream activist acts to get people to dream more
debt crisis when I get my credit card statements
disney is a great company
dance everyone DANCE
dancing with the stars or dancing with the star
dadt, don’t ask don’t tell what?
depression is depressing
diabetes is bad for you
drama on Law & Order
drd I have no idea what that is
digital is black and white
discrimination is bad for humans
diversity is good for humans
eds pick of movies
education is a good thing
entertainment is fun
elizabeth edwards was a good women
economy is excellent
election of Obama, awesome
e-mail is good for everyone except for post office
ethics see https://www.acm.org
exercise using Ubisoft
ebooks are fun
elnes no idea
e book good
facebook good and fun
film on a surface of water is ok unless it is oil
family is necessary
football fantasy
funny girl, funny boy
food good to eat
fashion excellent
favorite person
fox news good viewer numbers
fox good viewer numbers unless it is X-Files guy
fda food and drug administration
finance a new car for FREE?
fantasy finance a new for Free?
froyo what is that?
foursquare stalker net
fiction consultant’s status reports
folk hero
flash is a fast super hero
families are good to have
fringe elements in the population
google is a large number
gifts get them, give them, free stuff
groupon wow, a billion dollars worth of free stuff
gift for your mom
government shrink it
guide to better living for free
gaming is this gambling
holidays let’s share the fun free stuff
health and other things
holiday fun
humor funny
history of the universe
hardcover soft cover they are all books
holiday shopping is a fun thing to do
horror of whatever
humour the British mis-spelling of Humor
high school the best 5 years of my life
harry reid Senator
hd harddrives are being replaced by
haiti is half of an island
heroes are cool
howard cosell is dead and will remain so for a while
holiday music is nice in small doses
hip hop music is nice in small does
indie films are weird
internet is big
independent people are disconnected
iphone is a cellphone
ipad could be an electric fork
israel is a country in the Middle East, or is it the Middle West?
itunes is a music site
interviews of a hip hop artist who sings holiday music
interview of one of the Lead Atoms at the CERN
immigration reform really?  Ask an immigrant
ice Likely something to do with immigration
ireland crisis when hasn’t Ireland had a crisis
interviews from the edge of tomorrow
iran is sometimes called Persian, not sure why
jazzed up and dressed up
jazz is a form of music
julian assange is the Wikileaks guy
jets are fast
jimmy zuma from Yuma
journalism is a newsmaker
kids are fun to have
kindle is a way to read ebook, ebooks, or e books
kidtunes are for kids
kidlit no idea
kate middleton who?
kansas is a state
ktuu no way
katie couric short, rich and losing viewers
love is splendid thing
literature is something we read
music listen to it
movie nice to watch
mp3 listen to it and put it into XNA Games
movies multiple of movie
money green in the US
marketing a way to make money and to inform people
murder if you murder me you aren’t my friend anymore
mystery Mr. Mustard did it
mobile moving around
mastercard is a credit card
movie trailers are pulled by movie trucks
metal is good to use in vehicles
microsoft is a nice place to work and makes great software
middle class is a good place to be
nfl national football league
news of the universe
nonfiction and fiction are fun to read
new release of this or that
national football league nfl
nutrition is good to eat
nook and cranny
nba national basketball league
nostalgia for the past
netflix is good for people who like Lois and Clark
nintendo games are weak
new york is a city, county and state
obama is the first name of the president
obesity is fattening
opinion keep it to myself
online education is a good idea
ohio is a state
online shopping can save money
politics a place for people who can’t do calculus
paperback paperforward
pop goes the weasel
prince william is a bonny fellow
pga tour for golfers
picks and takes
parenting is fun
pro dev audience
poverty sucks
photography is a way to show off your talent
privacy is private
patriots are good
preview of the Yogi Bear movie
pat downs and sally forth
peace and apple pie
pbs public broadcasting system
parody of real life
paypal is a way to pay for things
president obama plays basketball
phil mickelson who?
palin a candidate for the one Mars trip
paul mccartney sings music
promise arizona that the air will be dry
president and residents differ
physics CERN and other places
review physics paper
rock scissors and paper
relationships are nice to have at Christams
retail stores are having a good year
religion is nice for many people, others not so much
republican is a political party
research in physics
recipes for small basic
recession is bad
recycle is good
reduce spending in Sacramento
romance and love
rory mcilroy who?
reuse and recycle
real estate is property
reference a property in a program
restaurants and food trucks
republicans are a political party
social media like facebook
sarah palin candidate for Mars Mission
security is a good thing
social networking using facebook
shopping for presents at Christmas time
science is interesting
softcover hardcovers are both books
sex of birds, how do you tell?
sony is a company with great products
scifi is science fiction
small business is the engine of the US Economy
streaming videos are a good idea
sports are fun
samsung makes a fine Windows Phone 7
science fiction or scifi
snow is cold and fun for about a day
sexuality in birds, feathers and displays
scrubclub that’s weird
scanners live in vain
software is a way to make money
society something we have to put up with
scott is a person’s name
television is something to veg out in front of
tv another name for television
travel to another country
twitter is fun for some people
tsa necessary for secure air travel
technology is what makes the world go round
thanksgiving is a way to gain weight
tiger woods is a golfer
tom brady who?
target Roundel
tea party for the Mad Hatter
terrorism is terrible
teachers are underpaid
tmz is a nosy website
texas is a state with it’s act together
underdog is here to save the day
uk united kingdom
u.k. united kingdom again
video of professors talking
veterans of foreign ward
verizon is a company
video games are fun to build using XNA
visa is a credit card
violence against women is bad
weight loss is good unless you have cancer then it’s bad
wikileaks could be renamed
wam golf what is wam golf?
women are beautiful
war is bad for living things
white house is in Washington D.C.
westboro baptist church is a good place
washington redskins are a football team
x ray is a radiation
youtube is a video presentation web site
yasni have no idea

NNNN

IsoStoreDemo.zip