Question

when I read file with binary reader:

using (FileStream FilStr = new FileStream(MainPreferenceModel.Instance.PrintHeader.CompanyLogoFilePath, FileMode.Open))
{
    using (BinaryReader BinRed = new BinaryReader(FilStr))
    {
        HeaderFooterReportModel.Logo = BinRed.ReadBytes((int)BinRed.BaseStream.Length);
        BinRed.Close();
    }
    FilStr.Close();
}

It is OK, but when opening file e.g. C:\logo.jpg it throw exception. Is posible to Get UAC prompt only for reading this file? -user use FileOpenDialog to get path.

I found way how to run program as Admin on startup, but is there way how to get access to file on path like this? I can copy that file to some other path via run command as admin, but its not solution for this.

Thanks for reply

Was it helpful?

Solution

  using (FileStream FilStr = new FileStream(path, FileMode.Open))

The real problem here is that you are not specific enough about the access you want to the file. The way you wrote it, you leave it up to FileStream to select a file access. And it will pick FileAccess.ReadWrite. You are not going to get that on the C:\ directory, it is protected for write access without UAC elevation. And you don't need it, you are only reading from the file.

Fix:

  using (FileStream FilStr = new FileStream(path, FileMode.Open, FileAccess.Read))

OTHER TIPS

Elevation is performed at process startup only. So there is no way to elevate during the life of a process. You have to decide once and for all at startup.

What applications typically do is to start new processes to perform specific tasks that require elevation. You can start a new instance of the application passing command line arguments and using the runas verb to request elevation. Or you can use an elevated out-of-process COM server to do the work. The former is quicker to set up, but the latter is a cleaner solution.

You have to create/modify your application manifest like in this Microsoft example (for an assembly called IsUserAdmin.exe):

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> 
  <assemblyIdentity version="1.0.0.0"
     processorArchitecture="X86"
     name="IsUserAdmin"
     type="win32"/> 
  <description>Description of your application</description> 
  <!-- Identify the application security requirements. -->
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel
          level="requireAdministrator"
          uiAccess="false"/>
        </requestedPrivileges>
       </security>
  </trustInfo>
</assembly>

More info here: http://msdn.microsoft.com/en-us/library/bb756929.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top