All about WP7 Isolated Storage - Read and Save Binary files
published on: 4/26/2011 | Views: N/A | Tags: IsoStore
by WindowsPhoneGeek
This is the 9th article from the "All about WP7 Isolated Storage " series of short articles focused on real practical examples with source code rather than a plain theory. I am going to talk about how to read and save Binary files into Isolated Storage.
Binary files are usually thought of as being a sequence of bytes. Generally a binary file may contain any type of data encoded in binary form. For example: .mp3 file, .jpg file, .txt file, .db, etc. can be thought as binary files.
- All about WP7 Isolated Storage - intro to Isolated Storage
- All about WP7 Isolated Storage - Creating Folders and files
- All about WP7 Isolated Storage - Store data in IsolatedStorageSettings
- All about WP7 Isolated Storage - Read and Save Text files
- All about WP7 Isolated Storage - Read and Save XML files using XmlSerializer
- All about WP7 Isolated Storage - Read and Save XML files using XmlWriter
- All about WP7 Isolated Storage - Read and Save Images
- All about WP7 Isolated Storage - Read and Save Captured Image
- All about WP7 Isolated Storage - Read and Save Binary files
- All about WP7 Isolated Storage - File manipulations
- All about WP7 Isolated Storage - Recommendations and Best Practices
- All about WP7 Isolated Storage - open source Databases and Helper libraries
To begin with lets first create a Windows Phone 7 application project and add a sample .mp3 file (in our case Battery_Low.mp3 attached at the end of this article).
After that include the following namespaces in MainPage.xaml.cs (alternatively you can use the code in another page):
using System.IO.IsolatedStorage; using System.IO; using System.Windows.Resources;
Save .MP3 File to Isolated Storage
In this example at first we will check if the file already exists and after that we will save the Battery_Low.mp3 file to the IsolatedStorage.
Basically at first we create a stream out of the sample .mp3 file and after that a virtual store. Next we use BinaryWriter and BinaryReader to create a new .mp3 file into Isolatedstorage(create a new file into IsolatedStorage and copy the data from Battery_Low.mp3 into the newly created one). Note that we read the file in chunks in order to reduce memory consumption and increase performance!
private const string FileName = "Battery_Low.mp3";
private void btnSave_Click(object sender, RoutedEventArgs e)
{
StreamResourceInfo streamResourceInfo = Application.GetResourceStream(new Uri(FileName, UriKind.Relative));
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(FileName))
{
myIsolatedStorage.DeleteFile(FileName);
}
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(FileName, FileMode.Create, myIsolatedStorage))
{
using (BinaryWriter writer = new BinaryWriter(fileStream))
{
Stream resourceStream = streamResourceInfo.Stream;
long length = resourceStream.Length;
byte[] buffer = new byte[32];
int readCount = 0;
using (BinaryReader reader = new BinaryReader(streamResourceInfo.Stream))
{
// read file in chunks in order to reduce memory consumption and increase performance
while (readCount < length)
{
int actual = reader.Read(buffer, 0, buffer.Length);
readCount += actual;
writer.Write(buffer, 0, actual);
}
}
}
}
}
}
NOTE: When working with files always use Using statement because it provides a convenient syntax that ensures the correct use of IDisposable objects.
Read .MP3 File from Isolated Storage
In this example at first open an existing Battery_Low.mp3 file from the Isolated Storage and read its content. After that the content is set as a source of MediaElement control.
private void btnRead_Click(object sender, RoutedEventArgs e)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(FileName, FileMode.Open, FileAccess.Read))
{
this.mediaElement.SetSource(fileStream);
}
}
}
NOTE: When open an existing file from the Isolated Storage we use FileMode.Open, when we want to read to a file we useFileAccess.Read! You can find a list of all FileAccess possibilities here.
NOTE: "mediaElement" is a MediaElement placed inside MainPage.xaml: <MediaElement x:Name="mediaElement" AutoPlay="True"/>
In this article I talked about reading and saving binary files(.mp3 file) into Isolated Storage. Here is the full source code:
Stay tuned with the rest of the posts. I hope that the article was helpful.
You can also follow us on Twitter @winphonegeek
Comments
Problem faced
posted by: Mohamad on 6/7/2011 3:46:21 PM
I faced a problem in this line int actual = reader.Read(buffer, 0, buffer.Length); every time the actual returns a zero value and so I am in infinite while loop. Can any one help me to know what is my problem ?
Duration
posted by: MohamadHotait on 6/8/2011 1:13:04 AM
Why we cannot retrieve the duration of the music after reading the music file ?
Problem faced, answer
posted by: Jay on 7/1/2011 11:52:45 PM
Regarding
int actual = reader.Read(buffer, 0, buffer.Length);
returning zero, you probably just need to seek the stream to zero before using it.
Cannot hear sound on phone
posted by: George_Greece on 8/17/2011 2:25:56 AM
First of all thank you for your wonderful article. It really helped me to learn a lot of things. I tried this example on the emulator and it worked pretty good. But when i deployed the app on a real device i could not hear the sound. Does anyone know why this is happening?
Thanks...
Our Top Articles & Free books
- Our FREE e-book: "Windows Phone Toolkit In Depth" 2nd edition
- 400+ Windows Phone Development articles in our Article Index
- 21 WP7 Toolkit in Depth articles covering all controls
- 12 WP7 Coding4Fun Toolkit in Depth articles covering all controls
- Performance Tips when creating WP7 apps
- Creating a WP7 Custom Control in 7 Steps
- WP7 working with VisualStates: How to make a ToggleSwitch from CheckBox
- What makes a WP7 App successful
- Creating theme friendly UI in WP7 using OpacityMask
- Implementing Windows Phone 7 DataTemplateSelector and CustomDataTemplateSelector
- All about Splash Screens in WP7 – Creating animated Splash Screen
- Getting Started with Unit Testing in Silverlight for WP7
- WP7 WatermarkedTextBox custom control
Our Top Tips & Samples
- All about WP7 Isolated Storage series
- WP7 Dynamically Generating DataTemplate in code
- 5 tips for a successful WP7 Marketplace submission
- WP7: Navigating to a page in different assembly
- WP7 ContextMenu: answers to popular questions
- WP7 ListBox: answers to popular questions
- WP7 working with Images: Content vs Resource build action
- WP7 Element Binding samples
- WP7 working with XML: reading, filtering and databinding
- Drawing in WP7: #2 Drawing shapes with finger
- WP7 TextBox Light theme problems - the solution
- Changing the WP7 Panorama Background Image dynamically with Animation
