Welcome!

@DXWorldExpo Authors: Liz McMillan, Elizabeth White, Zakia Bouachraoui, Pat Romanski, Maria C. Horton

Blog Feed Post

Android to Windows 8: Working with Files

Learn how to write code in Windows Store apps for Windows 8 to save files, like photos or documents. You can store these files in app-specific file locations or save them to external storage media, like a USB drive.

A user may want to save a document that they’re working on and immediately return to the saved document it when they return to some document editor app. Or a user may want to save the current photo from some photo editing app to a USB drive and then connect that USB drive to a TV or a digital picture frame to view later. You can help your users do this by saving the document to an app-specific location on the user’s device, and by saving the photo to external storage media.

Here’s how app-specific file storage works behind the scenes in Windows Store apps. Each app can store files to a separate set of directories (called the local, roaming, and temporary directories) on a particular device:

· The local directory contains files that exist only on the local device.

· The roaming directory contains files that exist on all devices where the user has installed the app.

· The temporary directory is like the local directory, but the system can remove its files at any time.

When a user installs a Windows Store app, Windows automatically creates these directories. You don’t need to worry about where to find them because Windows tracks them for you. You just use the ApplicationData class to access them. If the user ever uninstalls the app, Windows automatically removes the matching directories so you don’t even have to worry about cleaning them up.

Windows tip
If a user wants to store app-specific files that are particularly valuable or irreplaceable, have your app store them in a more permanent location instead, like the user’s SkyDrive.

To store files in external storage media, you can use the DeviceInformation and StorageDevice classes. More about that later.

Here’s how to do all of this in code.

Save a file to an app-specific directory

In a Windows Store app, to save a file named hello.txt, write code like this for the local directory.

var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Hello.txt");
await FileIO.WriteTextAsync(file, "Hello world!");

Or write code like this for the roaming directory.

var file = await ApplicationData.Current.RoamingFolder.CreateFileAsync("Hello.txt");
await FileIO.WriteTextAsync(file, "Hello world!");

And you can write code like this for the temporary directory.

var tempFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("TempFile.txt");
Android tip
In Android apps, write code like this for the local directory.

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

outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());outputStream.close();

Set the file-creation mode to MODE_PRIVATE so that other apps can’t access your app’s files. Windows Store apps, in contrast, can access only their own files.

Write code like this for the temporary directory.

File tempFile;
tempFile = File.createTempFile("TempFile.txt", null, context.getCacheDir());

Saving a File to External Storage

In a Windows Store app you must declare the Removable Storage capability in the in the Package.appsxmanifest associated with your app

After you declare this capability, check to see if external storage media is available using code like this.

public async Task<bool> IsExternalStorageAvailable()
{
  var devices = await DeviceInformation.FindAllAsync(StorageDevice.GetDeviceSelector());
   if (devices.Count > 0)
    return true;
   else
    return false;
}

If the external storage media is available, create the file using code like this.

var storage = StorageDevice.FromId(deviceInformation.Id);
await storage.CreateFileAsync("HelloWorld.png");
Android tip
In Android apps, to do something similar, first request the WRITE_EXTERNAL_STORAGE permission in your app’s manifest, like this.

<manifest>
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>

After you request this permission, check to see if external storage media is available, using code like this.

public boolean isExternalStorageWritable() {    
 String state = Environment.getExternalStorageState();
 if (Environment.MEDIA_MOUNTED.equals(state)) {
   return true;
 }
  return false;
}

If the external storage media is available, you can then create the file. For example, to create a file in the media’s Pictures directory, write code like this.

File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "HelloWorld.png");

Next steps

To learn more about saving files, see these resources.

Read the original blog entry...

More Stories By Adam Grocholski

Hey there! My name is Adam Grocholski, and I'm a Technical Evangelist at Microsoft where I spend time focusing on Windows, Windows Phone, and Windows Azure. I live in the frozen tundra of Minnesota and run thinkfirstcodelater.com. You can also follow me on twitter at @codel8r.

DXWorldEXPO Digital Transformation Stories
@CloudEXPO and @ExpoDX, two of the most influential technology events in the world, have hosted hundreds of sponsors and exhibitors since our launch 10 years ago. @CloudEXPO and @ExpoDX New York and Silicon Valley provide a full year of face-to-face marketing opportunities for your company. Each sponsorship and exhibit package comes with pre and post-show marketing programs. By sponsoring and exhibiting in New York and Silicon Valley, you reach a full complement of decision makers and buyers in ...
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound e...
"Cloud computing is certainly changing how people consume storage, how they use it, and what they use it for. It's also making people rethink how they architect their environment," stated Brad Winett, Senior Technologist for DDN Storage, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
Rodrigo Coutinho is part of OutSystems' founders' team and currently the Head of Product Design. He provides a cross-functional role where he supports Product Management in defining the positioning and direction of the Agile Platform, while at the same time promoting model-based development and new techniques to deliver applications in the cloud.
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settl...
"We were founded in 2003 and the way we were founded was about good backup and good disaster recovery for our clients, and for the last 20 years we've been pretty consistent with that," noted Marc Malafronte, Territory Manager at StorageCraft, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
LogRocket helps product teams develop better experiences for users by recording videos of user sessions with logs and network data. It identifies UX problems and reveals the root cause of every bug. LogRocket presents impactful errors on a website, and how to reproduce it. With LogRocket, users can replay problems.
Data Theorem is a leading provider of modern application security. Its core mission is to analyze and secure any modern application anytime, anywhere. The Data Theorem Analyzer Engine continuously scans APIs and mobile applications in search of security flaws and data privacy gaps. Data Theorem products help organizations build safer applications that maximize data security and brand protection. The company has detected more than 300 million application eavesdropping incidents and currently secu...