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

限于喜欢 提交于 2019-12-05 01:03:01

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/5045456/how-to-read-text-from-a-text-file-in-the-xap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!