将属性添加到属性后查找文件路径

时间:2014-02-20 01:22:49

标签: c# image visual-studio-2013

将属性添加到属性后尝试查找文件的路径效果不佳。在我的属性中,文件如下所示:

internal static System.Drawing.Bitmap one {
        get {
            object obj = ResourceManager.GetObject("one", resourceCulture);
            return ((System.Drawing.Bitmap)(obj));
        }
    }

如何找到此文件的路径? 然后我尝试使用它:

System.Reflection.Assembly thisExe;
        thisExe = System.Reflection.Assembly.GetExecutingAssembly();
        System.IO.Stream file =
            thisExe.GetManifestResourceStream("WindowsFormsApplication1.Properties.Resources.one");
        this.pictureBox1.Image = Image.FromStream(file);

当我运行此代码时:

System.Reflection.Assembly thisExe; 
thisExe = System.Reflection.Assembly.GetExecutingAssembly();
string [] resources = thisExe.GetManifestResourceNames();
string list = "";

// Build the string of resources.
foreach (string resource in resources)
list += resource + "\r\n";

它给了我以下路径:" WFA1.Form1.resources"和" WFA1.Properties.Resources.resources"

可以补充我的资源是嵌入的。

如果您需要更多信息,请告诉我。

所以我想要的是我的文件的路径,或者我如何找到路径的信息。环顾四周之后,他们说这应该有效:

System.IO.Stream file =
            thisExe.GetManifestResourceStream("[WindowsFormsApplication1.Form1.resources].[a.jpg]");

IE:

System.IO.Stream file =
            thisExe.GetManifestResourceStream("[Namespace].[file and extension]");

所以看起来我的命名空间错了cus它仍然在这一行返回null:

this.pictureBox1.Image = Image.FromStream(file);

1 个答案:

答案 0 :(得分:2)

我已经看过这个了,我不相信有一种方法可以在没有严格的字符串构建/操作的情况下获得路径。这当然会导致更大的问题。

我认为这段代码是不够的:

var bmp = new Bitmap(WindowsFormsApplication1.Properties.Resources.one);
pictureBox1.Image = bmp;

而不是这一个:

var thisExe = Assembly.GetExecutingAssembly();
var file = thisExe.GetManifestResourceStream("WindowsFormsApplication1.Properties.Resources.one");
if (file != null) pictureBox1.Image = Image.FromStream(file);

选项2:

var assembly = System.Reflection.Assembly.GetExecutingAssembly(); 
var stream =  assembly.GetManifestResourceStream("WindowsFormsApplication1.Properties.Resources.one.jpg");
var tempPath = Path.GetTempPath(); 
File.Save(stream, tempPath);