开发者

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?


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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜