Android to Windows Phone 8: Working with Files

May 28, 2013

Over the next several posts I’ll show you how to work with local data on the Windows Phone 8 platform and compare it to working with data on the Android platform.

Windows Phone allows you to create, read, and delete files on the device’s internal storage.

Creating a File

To create a file called hello.txt in Android, you would write code similar to the following:

String filename = "hello.txt";
String string = "Hello world!";
FileOutputStream outputStream;

outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
Android tip
In Android to ensure other apps can’t read your app’s files you have to set its file mode MODE_PRIVATE. Windows Phone apps run in a sandbox. As a result apps cannot access one another’s files.

To create the same file in a Windows Phone app you leverage the StorageFile class and the Stream class.

string text = "Hello world!";
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(text.ToCharArray());

StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("Hello.txt", CreationCollisionOption.ReplaceExisting);

using (var stream = await file.OpenStreamForWriteAsync())
{
 stream.Write(fileBytes, 0, fileBytes.Length);
}
Windows Phone tip
Do not be tempted to use the RoamingFolder and/or TemporaryFolder properties of the ApplicationData class in place of the LocalFolder property. While the API’s are available to call, they have not been implemented in Windows Phone 8. An exception will be thrown if they are called.

Reading a File

To read the content of the hello.txt file in Android you leverage the BufferedReader class.

String filename = "hello.txt";

BufferedReader reader = new BufferedReader(new FileReader(filename));

String currentLine = null;

StringBuilder builder = new StringBuilder();

while((currentLine == reader.readLine()) != null){
 builder.append(currentLine);
 buidler.append("\n");
} 

String text = builder.toString();

In Windows Phone you use the StreamReader class.

string filename = "Hello.txt";

StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;

Stream stream = await local.OpenStreamForReadAsync(filename);

using (StreamReader reader = new StreamReader(stream))
{
 string text = reader.ReadToEnd();
}

Deleting a File

To delete a file called hello.txt in Android you simply instantiate a File object using the path to the file and call its delete method.

String filename = "hello.txt";
File file = new File(filename);
file.delete();

In Windows Phone you do something very similar. The main difference being you first need to get a reference to the folder the file is in.

string filename = "Hello.txt";
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile file = await local.GetFileAsync(filename);
await file.DeleteAsync();

Additional Resources