![](/img/trans.png)
[英]WinApi - GetLastError vs. Marshal.GetLastWin32Error
[英]Marshal.GetLastWin32Error() throws Access Denied in UWP C#
我的UWP應用中有以下代碼
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;
}
}
但是,當我嘗試從MainPage.xaml.cs訪問它時,出現了“拒絕訪問”的提示。 將Visual Studio 2015社區切換到管理模式也無濟於事
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
try
{
DeviceIoControlHelper.ReturnFileHandler();
}
catch(Exception ex)
{
}
}
}
我在Visual Studio 2015社區中將UWP與C#一起使用
您將需要使用CreateFile2通過通用Windows應用程序打開文件。 但是,它不允許您打開設備。 引用MSDN: 從Windows Store應用程序調用時,CreateFile2得到簡化。 您只能在ApplicationData.LocalFolder或Package.InstalledLocation目錄中打開文件或目錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.