Saturday, January 19, 2013

Reading files in Silverlight Application

There was a request to read information from a text file in my silverlight application. When I did the coding and testing, I tried to hardcode the path and read the file using "StreamReader" class. This was not working because silverlight was throwing security exception error.

After some trial and error, I discovered that the user must be prompted to select a file and only that selected file can be read through the application.

Here is the sample code.

private void Load_Click(object sender, RoutedEventArgs e)
{
Stream fs = null;
try
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "xml files (*.xml)|*.xml";
ofd.Multiselect = false;
bool? userClickedOK = ofd.ShowDialog();
if (userClickedOK == true)
{
fs = ofd.File.OpenRead();
using (System.IO.StreamReader reader = new System.IO.StreamReader(fs))
{
XmlReader xmlReader = XmlReader.Create(reader);
List<GraphicObject> savedGraphics = XMLDeserialize<List<GraphicObject>>(xmlReader);
DisplayAllGraphicsData(savedGraphics);
this.graphicsLayer.Refresh();
fs.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
}
}

The "using" statement is the key here. Any file reading must happen inside this "using" block.

Hope this tip helps!

Cheers
Anand

All Blogs so far ...