Nick Heiner
Nick Heiner

Reputation: 122520

File Permissions Issue with Silverlight

I have a Silverlight 4 / C# project I'm working on in Visual Studio. I made an XML data file by right clicking on the project >> Add New Item >> Xml File. I then try to open the file:

        StreamReader streamReader = new StreamReader("data.xml");

However, this gives a security exception. How can I get around this, or grant the necessary permissions?

Upvotes: 1

Views: 1484

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1501896

Do you just need to be able to read the file at execution time? If so, I would suggest you set it to have a Resource build action in Visual Studio, and then use Assembly.GetManifestResourceStream to open it. That's the simplest way of bundling read-only data with an application, IMO.

Upvotes: 2

Aaron McIver
Aaron McIver

Reputation: 24723

You would need to mark the item as a resource, NOT an embedded resource.

From MSDN...

The Properties window in Visual Studio provides several other values in the Build Action drop-down list. However, you can use only the previous three values with Silverlight projects. In particular, Silverlight embedded resources must always use the Resource build action, and not the Embedded Resource build action, which uses a format that Silverlight cannot recognize.

A great walk through can be seen here entailing what you are trying to accomplish. Since you are not trying to access files on disk but as resources this is not a problem. IsolatedStorage nor elevated permissions are pertinent here.

Upvotes: 2

AnthonyWJones
AnthonyWJones

Reputation: 189487

That constructor of StreamReader is expecting a file path into the local file system, which is only available out of browser with elevated trust.

Instead you should be using Application.GetResourceStream:-

Stream stream = Application.GetResourceStream(new Uri("data.xml", UriKind.Relative));
StreamReader reader = new StreamReader(stream);

However I expect you really just want this in an XDocument, you bypass this StreamReader stage:-

XDocument doc = XDocument.Load(stream);

BTW, I personally would leave the XML as Content in the Xap rather than embedding it in the assembly.

Upvotes: 1

driis
driis

Reputation: 164331

Silverlight doesn't allow local file system access by default. Your options are:

If you need to store data in general, use IsolatedStorage if you can.

Upvotes: 2

Related Questions