如何从XAP中的文本文件读取文本? [英] How to read text from a text file in the XAP?

查看:85
本文介绍了如何从XAP中的文本文件读取文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个浏览器外的Silverlight程序,并且已经成功地通过OpenFileDialog使其打开了本地文件。但是,现在我需要它从其自己的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();
}

此代码引发 SecurityException 显示不允许进行文件操作。拒绝访问路径'Default.txt'。我在做什么错?

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

推荐答案

您的代码正在尝试打开名为 Default.txt的文件,该文件位于用户的文件系统。我确切不知道的地方,这取决于Silverlight应用从何处执行。所以是的,通常来说,您没有权限去那里。

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.

要从XAP中提取内容,您需要以不同的方式构造流。它将遵循以下原则:

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

注意,这意味着您的Default.txt应该设置为资源,而不是嵌入式资源 。作为资源,它将被添加到XAP。嵌入式资源会将其添加到程序集中。

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.

更多信息: http://nerddawg.blogspot.com/2008/03/silverlight-2-demystifying-uri.html

注意:如果您的Silverlight程序具有多个程序集,请检查Uri字符串的 / MyXap部分是否引用了包含该资源的程序集的名称。例如,如果您有两个程序集 ProjectName和 ProjectName.Screens,其中 ProjectName.Screens包含您的资源,则使用以下程序:

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

这篇关于如何从XAP中的文本文件读取文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆