WPF Application Crash After running from C:\Program Files (x86)\ OR by C:\Program Files

StackOverflow https://stackoverflow.com/questions/19180402

  •  30-06-2022
  •  | 
  •  

سؤال

i have made an application in WPF , which is calling data via REST API by making request & getting Response , After getting Response I am downloading all the Image files & encrypting it & saving on my local drive & putting path of local encrypted Image in my Local DB which is in my application (SQL server Compact 4.0).

All of above process is running in background Thread .

Now the presentation layer of application always look up in to local DB, if get any Image path the application decrypt it by following way & use it to display on presentation layer.

Image img_home = new Image();
img_home.Width = 1920;
img_home.Height = 1080;  
img_home.Source = DecryptFile.LoadBitmapImages(mediaPath); 
grid_main_Home_page.Children.Add(img_home);

//where grid_main_Home_page is a Grid in application

public static BitmapSource LoadBitmapImages(string ImagePath_to_Save)
{
    byte[] ImageBytes;
    BitmapSource bs1;
    // if (File.Exists(ImagePath_to_Save))
    //{
        ImageBytes = File.ReadAllBytes(ImagePath_to_Save);
        using (System.IO.MemoryStream Stream = new System.IO.MemoryStream(ImageBytes))
        {
            Bitmap source = new Bitmap(Stream);
            IntPtr ip = source.GetHbitmap();
            bs1 = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, Int32Rect.Empty,

            System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

            return bs1;
        }
    // }
}

My application working fine when i am running application directly by .exe any where in my machine.

As i am running my application by C:\Program Files (x86)\ OR by C:\Program Files , it is going to crash by showing following error--enter image description here

as I am looking in the directory the Image file is exits , If i am putting that part of code in try catch block but still getting same error .

If I am putting image source like

img_home.Source =new BitmapImage(new Uri(mediaPath,UriKind.Absolute)); 

it's working fine , but i don't want it because here i need to decrypt & save the file in local drive .

Please help me , i am struggling on it .

Regards

Anupam mishra

هل كانت مفيدة؟

المحلول

You cannot write to the Program Directory in Windows versions newer than Windows XP. And that's a good thing. There is a special folder for user data. You can query it and save your data there:

// Sample for the Environment.GetFolderPath method 
using System;

class Sample 
{
    public static void Main() 
    {
       var folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
       Console.WriteLine(folder);
       Console.ReadLine();
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top