日期:2014-05-16  浏览次数:20726 次

WPF,访问程序集资源的问题

在WPF项目中,添加了一个pp.txt文档,使用了默认的生成操作"Resource",复制到输出目录为"不复制",于是,下面的代码会找不到文件:

private void Button_Click(object sender, RoutedEventArgs e)
{
    string s1 = "pp.txt";
    if (!File.Exists(s1))  //确定指定的文件是否存在
    {
        MessageBox.Show("文件不存在");
        return;
    }
    else
        MessageBox.Show("文件存在");
}

于是,我把复制到输出目录修改成"始终复制",并且也看到了应用程序目录中确实有pp.txt文件,但是运行上面的代码,结果还是弹出"文件不存在",请问,这是什么原因呢?

------解决方案--------------------
加Applistation.StartPath
------解决方案--------------------
txt文件不应该作为资源文件,你应该将它设置成Content,并设置 Copy if newer


* None: 此文件不参与编译也不被输出。比如:工程中的文档文件, readme.txt。

* Compile: 参与编译并输出。主要是代码文件。

* Content: 不参与编译,但会被输出。

* Embedded Resource: 此文件被嵌入到主工程生成的DLL或exe中。主要是资源文件。

* ApplicationDefinition: 和Page类似,但只用于Silverlight的启动页面(默认是App.xaml)。

* Page: Silverligh中所有的usercontrol/page/childwindow xaml都属于"Page” build,其它的build action不能将code behind文件和xaml文件连接起来。

* CodeAnalysisDictionary: 自定义的CodeAnalysis字典。(参考http://blogs.msdn.com/b/codeanalysis/archive/2007/08/20/new-for-visual-studio-2008-custom-dictionaries.aspx)

* Resource:embeds the file in a shared (by all files in the assembly with similar setting) assembly manifest resource named AppName.g.resources

* SplashScreen: Silverlight的欢迎界面。

* DesignData: Sample data types will be created as faux types. Use this Build Action when the sample data types are not creatable or have read-only properties that you want to defined sample data values for.

* DesignDataWithDesignTimeCreatableTypes: Sample data types will be created using the types defined in the sample data file. Use this Build Action when the sample data types are creatable using their default empty constructor.

* EntityDeploy: 适用于Entity框架。
------解决方案--------------------
引用:
Quote: 引用:

加Applistation.StartPath

为什么要加,MSDN上明明说的可以是相对路径,况且System.Window命名空间中的Applistation并没有StartPath属性啊。

此处相对的目录是bin\debug文件夹,你要看你的debug文件内有没有这个txt文件
------解决方案--------------------
那你需要设置它成 Embedded Resource,并设置 Copy if newer
------解决方案--------------------
http://msdn.microsoft.com/zh-cn/library/aa970494(v=vs.110).aspx
------解决方案--------------------
设为resource的文件,在编译时会参与编译,并嵌入到AppName.g.resources文件内

而txt,mp3,video这些文件没必要参与编译
------解决方案--------------------
引用:
那你需要设置它成 Embedded Resource,并设置&nbs