0

I have the below code in my UWP app

public static class DeviceIoControlHelper
    {
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
        private static extern SafeFileHandle CreateFile(
           string lpFileName,
           [MarshalAs(UnmanagedType.U4)] FileAccess dwDesiredAccess,
           [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode,
           IntPtr lpSecurityAttributes,
           [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition,
           [MarshalAs(UnmanagedType.U4)] FileAttributes dwFlagsAndAttributes,
           IntPtr hTemplateFile);

public static SafeFileHandle ReturnFileHandler()
        {
            const string drive = @"\\.\LCD";

            SafeFileHandle hddHandle = CreateFile(drive, FileAccess.Read, FileShare.None, IntPtr.Zero, FileMode.Open, FileAttributes.Normal, IntPtr.Zero);

            if (hddHandle.IsInvalid)
            {
                int lastError = Marshal.GetLastWin32Error();
                string errorMessage = string.Format(@"!! Invalid {0}; Error ({1}): {2}", drive, lastError, new Win32Exception(lastError).Message);
                throw new Win32Exception(errorMessage);
            }

            return hddHandle;
        }
}

But, when I try to access it from my MainPage.xaml.cs, I got an expcetion of "Access Denied". Switching Visual Studio 2015 Community to Admin mode did not helped either

public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();

            try
            {
                DeviceIoControlHelper.ReturnFileHandler();
            }
            catch(Exception ex)
            {

            }
        }
}

I am using UWP with C# in Visual Studio 2015 Community

Yeasin Abedin
  • 2,081
  • 4
  • 23
  • 41

1 Answers1

0

You will need to use CreateFile2 to open files with a Universal Windows application. It won't allow you to open devices, though. To quote MSDN: When called from a Windows Store app, CreateFile2 is simplified. You can open only files or directories inside the ApplicationData.LocalFolder or Package.InstalledLocation directories.

David Bremner
  • 396
  • 5
  • 8