遇到的问题
在使用WPF开发桌面EXE的过程中,遇到了Webview2无法往C盘写入文件的问题
解决思路
- 程序启动的时候使用代码给文件夹赋予高权限
- Webview2指定UDF
实践
本文讨论思路1的实现
C# 给文件夹赋权限
private void InitWebView2DirAccess()
{
try
{
string path = AppDomain.CurrentDomain.BaseDirectory;
string webview2DataDir = path + "WpfApp1.exe.WebView2";
Log.LogInfo.Info("InitWebView2DirAccess-webview2DataDir=" + webview2DataDir);
bool isModified = false;
DirectoryInfo dir2 = new DirectoryInfo(webview2DataDir);
//所有访问权限
System.Security.AccessControl.DirectorySecurity dirSecurity = dir2.GetAccessControl(AccessControlSections.All);
//文件ACL继承
InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
//追加Eereryone用户组完全控制权限
FileSystemAccessRule everyoneFileSystemAccessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
//追加Users用户组完全控制权限
FileSystemAccessRule usersFileSystemAccessRule = new FileSystemAccessRule("Users", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
dirSecurity.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out isModified);
Log.LogInfo.Info("isModified-1=" + isModified);
dirSecurity.ModifyAccessRule(AccessControlModification.Add, usersFileSystemAccessRule, out isModified);
Log.LogInfo.Info("isModified-2=" + isModified);
//设置访问权限
dir2.SetAccessControl(dirSecurity);
Log.LogInfo.Info("InitWebView2DirAccess-success");
}
catch (Exception ex)
{
Log.LogError.ErrorFormat(@"InitWebView2DirAccess-error:msg={0};堆栈={1}", ex.Message, ex.StackTrace);
}
}
|