Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using File.Open for a WPF Resource

Tags:

io

resources

wpf

I've got the following code below. High level overview is that it is a coverter that takes a .emf file from a file share, and then converts it into something WPF can use for Image.Source:

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var fileName = (string)value;
        if (fileName == null)
            return new BitmapImage();
        using (var stream = File.Open(fileName, FileMode.Open))
        {
            return GetImage(stream);
        }
    }

    internal BitmapImage GetImage(Stream fileStream)
    {
        var img = Image.FromStream(fileStream);
        var imgBrush = new BitmapImage();
        imgBrush.BeginInit();
        imgBrush.StreamSource = ConvertImageToMemoryStream(img);
        imgBrush.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
        imgBrush.EndInit();
        return imgBrush;
    }

    public MemoryStream ConvertImageToMemoryStream(Image img)
    {
        var ms = new MemoryStream();
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return ms;
    } 

Now, all is well and good here. The users are going to need a "print calibration" page, so I included a "SampleDoc.emf" file into my application and marked it as a resource.

However, I can't seem to get the File.Open() part right when pointing to that resource file. Any ideas on how I can do this?

like image 464
Jim B Avatar asked Jun 20 '26 03:06

Jim B


1 Answers

When you marked your "SampleDoc.emf" as a resource it only resides inside the compiled assembly (to put it very simply). See Getting additional files in LightSwitch which I asked and answerd a similar question which can answer your Question.

// creates a StreamReader from the TestFile.txt
StreamReader sr = new StreamReader(assembly.GetManifestResourceStream("SomeFile.txt"));

With this code you can access your resources.

Another way would be to mark the BuildOption for your File as "Content" and set the "copy action" to "copy always" or "only when newer" then your File gets copied to the outputdirectory when you build your Project.

like image 85
Stelzi79 Avatar answered Jun 23 '26 15:06

Stelzi79



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!