-1

I need to save the background of Form2 to file. It looks like there is a problem with Access to the path for save. It throws the following exception:

A generic error occurred in GDI+

It works when running the application as Administrator, but the program must work without Admin rights.

Here's my code:

Dim sPath As New SaveFileDialog
sPath.DefaultExt = ".\"

Dim bmp As New Bitmap(Form2.BackgroundImage)
Try
    'bmp = Form2.BackgroundImage
    bmp.Save(sPath.FileName + "image.png", System.Drawing.Imaging.ImageFormat.Png)
Catch ex As Exception
    MsgBox(ex.Message)
End Try

1 Answers1

0

As explained in the comments, a non-privileged user doesn't have access to the Program Files folder. So you have two options:

  1. Force your application to run as administrator: Check this answer. However, this is not recommended unless you actually need to have administrator rights.
  2. The other option is not to save in a folder that you don't have access to.

If it will not be possible to save the file to a folder with the program (Program Files), you don't know some alternative where the file should save without Admin Rights?

Well, that depends on what you're trying to save actually:

  • I see you're using a SaveFileDialog. If this is something the user would be saving, let the user select their preferred destination.
  • If not, and this is some kind of application data/settings, then you should save it in the application data folder ("%AppData%" or "%LocalAppData%"). These two folders don't require admin rights and they are the right place to store the data of your application.

    Here's an example of how you can use one of these foders:

    'Dim localAppDataDir As String = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
    Dim appDataDir As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
    Dim imagesDir As String = Path.Combine(appDataDir, Process.GetCurrentProcess().ProcessName, "Images")
    
    Dim imageFilePath = Path.Combine(imagesDir, "YourFilename.png")
    bmp.Save(imageFilePath)
    

    Note: in this case, you don't need the SaveFileDialog which I don't see any use for it in your code.