为什么测试文件夹中的文件不会删除??如何获得管理员访问权限??
namespace Delete
{
using System;
using System.Windows.Forms;
using System.IO;
public class Delete
{
public Delete()
{
if (Directory.Exists(@"C:\Program Files (x86)\test\"))
{
string[] filePaths = Directory.GetFiles(@"C:\Program Files (x86)\test\");
foreach (string file in filePaths) { File.Delete(file); }
}
}
}
}
发布于 2012-04-25 03:00:28
你需要重新考虑你的策略。
如果你在你的应用程序中以编程方式添加/删除文件,它们应该存储在一个单独的位置(这将不需要管理员权限来提升写入/删除等):
Program Files目录用于特定于应用程序的文件(DLL等),这些文件随程序一起安装,但在安装/更新后不会更改。
以下是按应用程序划分的用户数据目录的示例:
public static DirectoryInfo ApplicationVersionDirectory()
{
return new DirectoryInfo(System.Windows.Forms.Application.UserAppDataPath);
}
发布于 2012-04-25 02:40:48
这要归功于UAC。因此,您可以通过右键单击->“以管理员身份运行”来以管理员身份运行可执行文件,或者如果您希望以编程方式执行此操作,请参考其他帖子,如Windows 7 and Vista UAC - Programmatically requesting elevation in C#
发布于 2012-04-25 02:44:54
为了从"Program Files“文件夹中删除文件,您需要以管理员身份启动应用程序。否则,您将无法访问%PROGRAMFILES%。
以下是重启当前应用程序并以管理员身份运行的示例代码:
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.FileName = Application.ExecutablePath;
proc.Verb = "runas";
try
{
Process.Start(proc);
}
catch
{
// The user refused the elevation.
// Do nothing and return directly ...
return;
}
Application.Exit(); // Quit itself
https://stackoverflow.com/questions/10303914
复制相似问题