How to read text from a text file in XAP?

I am working on a Silverlight program other than a browser, and I successfully received it to open local files using OpenFileDialog. However, now I need to open the file from my own XAP (there is no need to view it, the file for opening is hard-coded). I am trying to use this code, but it does not work:

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

This code throws a SecurityException , which says: "File operation is not allowed. Access to the path" Default.txt "is denied." What am I doing wrong?

+4
source share
1 answer

Your code is trying to open a file called "Default.txt", which is located somewhere in the user's file system. Where exactly I do not know, as it depends on where the Silverlight application is running from. So yes, in general, you do not have permission to travel there.

To get something out of your XAP, you need to build a thread in a ton different ways. It will be as follows:

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

Note. This means that your Default.txt should be set to Resource, not Embedded Resource. Being a "resource", it will be added to XAP. Embedded Resource will add it to the assembly.

Additional information: http://nerddawg.blogspot.com/2008/03/silverlight-2-demystifying-uri.html

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

 new Uri("ProjectName.Screens;component/Path/To/Default.txt", UriKind.Relative)) 
+9
source

Source: https://habr.com/ru/post/1340371/


All Articles