Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read text from a text file in the XAP?

I'm working on an out-of-browser Silverlight program, and I have successfully gotten it to open local files by means of an OpenFileDialog. However, now I need it to open a file from within its own XAP (no browsing necessary, the file to open is hard-coded). I am trying to use this code, but it's not working:

using (StreamReader reader = new StreamReader("Default.txt"))
{
   TextBox1.Text = reader.ReadToEnd();
}

This code throws a SecurityException that says "File operation not permitted. Access to path 'Default.txt' is denied." What am I doing wrong?

like image 868
BCXtreme Avatar asked Jan 20 '23 10:01

BCXtreme


1 Answers

Your code is trying to open a file called "Default.txt" that is somewhere out in the user's file system. Where exactly I don't know, as it depends on where the Silverlight app's executing from. So yes, in general you don't have permission to go there.

To pull something out of your XAP, you need ton construct the stream differently. It will be along these lines:

Stream s = Application.GetResourceStream(
    new Uri("/MyXap;component/Path/To/Default.txt", UriKind.Relative)).Stream;
StreamReader reader = new StreamReader(s);

Note, this means your Default.txt should be set to 'Resource', not 'Embedded Resource'. By being a 'Resource' it will get added to the XAP. Embedded Resource will add it to the assembly.

More info: http://nerddawg.blogspot.com/2008/03/silverlight-2-demystifying-uri.html

Note: In cases where your Silverlight program has multiple assemblies, check that the "/MyXap" part of the Uri string references the name of assembly containing the resource. For example if you have two assemblies "ProjectName" and "ProjectName.Screens", where "ProjectName.Screens" contains your resource, then use the following:

new Uri("ProjectName.Screens;component/Path/To/Default.txt", UriKind.Relative))
like image 156
Matt Greer Avatar answered Jan 28 '23 09:01

Matt Greer