Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image Saving issue from Windows application c#

Tags:

c#

winforms

I have developed a win apps which save images in a specific folder from where our exe run from. The below I used to save images

protected string GetPath(string strFileName)
{
     string strPath=System.Environment.CurrentDirectory+@"\UPS\LabelImages\";
     if (!System.IO.Directory.Exists(strPath))
     {
          System.IO.Directory.CreateDirectory(strPath);
     }
     strPath = strPath + strFileName;
     return strPath;
}

the issue is some time win apps throwing execption like

Access to path 'C:\Windows\system32\UPS\LabelImages\' denied

suppose my application is installed inside c:\programfiles32 and then throw this kind of error my c# exe file. so tell me what would be the best option to save image files as a result no user get the exception or error like Access to path 'C:\Windows\system32\UPS\LabelImages\' denied

Looking for suggestion.

like image 498
Mou Avatar asked Jan 08 '23 04:01

Mou


2 Answers

I'd recommend saving those files in a safer location, such as the special folder for application data:

var safeFilePath = Path.Combine(Environment.GetFolderPath(
                       Environment.SpecialFolder.ApplicationData), @"UPS\LabelImages");

From the Environment.SpecialFolder doc:

ApplicationData: The directory that serves as a common repository for application-specific data for the current roaming user.

You could easily use another location too, as you see fit (i.e. MyDocuments or MyPictures).

Some locations on disk are a bad place to try saving files because of the potential for access errors like you're seeing, such as "System32", "Program Files", or the root C: directory, among others.

like image 190
Grant Winney Avatar answered Jan 10 '23 18:01

Grant Winney


May be you need to run your program as Administrator. To do so try to add this line in Properties/app.manifest file:

<security>
  <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
    <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
  </requestedPrivileges>

...

like image 21
Fabjan Avatar answered Jan 10 '23 18:01

Fabjan