没有权限删除文件的问题

问题描述:我在我的winform项目中尝试删除文件,但由于权限问题报错。错误提示如下
UnauthorizedAccessException: 对路径“C:\Program Files\Common Files\microsoft shared\ink\TabTip.exe”的访问被拒绝。

这个文件是一个软键盘文件,由于项目需要,我需要先把它先删除掉,然后从其它地方复制一个过来
我在网上找了一些方法,还是不行,比如:

                    string newPath = Path.Combine(basePath, "TabTip.exe");
                    //Get Currently Applied Access Control
                    FileSecurity fileS = File.GetAccessControl(newPath);
                    //Update it, Grant Current User Full Control
                    SecurityIdentifier cu = WindowsIdentity.GetCurrent().User;
                    fileS.SetOwner(cu);
                    fileS.SetAccessRule(new FileSystemAccessRule(cu, FileSystemRights.FullControl, AccessControlType.Allow));
                    //Update the Access Control on the File
                    File.SetAccessControl(newPath, fileS);
                    //Delete the file
                    File.Delete(newPath);

提问:怎样通过c#代码获取文件的删除权限呢,而不是通过手动添加权限去解决。恳请大家帮忙指点,感谢!

这个是微软操作系统中输入面板程序,属于系统程序,无法直接通过C#删除,建议换一种方式解决你的问题,而不是通过C#程序,需要你把你的实际需求描述准确一些

您可以使用 FileInfo 类来获取文件的读写和删除权限。
首先,创建一个 FileInfo 对象,并且使用它的 Exists 属性检查文件是否存在,然后检查它的 IsReadOnly 属性是否为 true,如果是,则表明文件为只读。
如果文件不是只读,则可以直接删除。如果是只读,您可以使用 FileInfo 对象的 SetAttributes 方法更改文件的属性,然后再尝试删除它。

以下是一个代码示例:

try
{
    FileInfo fileInfo = new FileInfo(@"C:\Program Files\Common Files\microsoft shared\ink\TabTip.exe");
    if (fileInfo.Exists)
    {
        if (fileInfo.IsReadOnly)
        {
            fileInfo.Attributes = FileAttributes.Normal;
        }
        fileInfo.Delete();
    }
}
catch (UnauthorizedAccessException ex)
{
    Console.WriteLine("Unable to delete file: " + ex.Message);
}

请注意,在删除文件之前,您应该首先检查您是否有权限删除文件,并且应该在执行操作时进行异常处理。

string filePath = "C:\example\file.txt";

// 获取文件的安全权限
FileSecurity fileSecurity = File.GetAccessControl(filePath);

// 添加一个新的文件访问规则
fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.Delete, AccessControlType.Allow));

// 移除一个文件访问规则
fileSecurity.RemoveAccessRule(new FileSystemAccessRule("Users", FileSystemRights.Delete, AccessControlType.Deny));

// 保存文件的新安全权限
File.SetAccessControl(filePath, fileSecurity);

您好,根据您描述的问题,c#程序提示没有权限删除的问题,可以尝试设置当前应用程序以管理员身份运行:
设置当前应用程序以管理员身份运行,即在VS的工程右键添加”应用程序清单文件“。右键添加,添加后,设置以管理员权限运行。

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

或者参考:
https://www.cnblogs.com/kybs0/p/9858779.html

望采纳,谢谢!
你可以使用File.SetAccessControl()方法来设置文件的访问权限,并使用FileSecurity类来设置文件的删除权限。例如:

FileSecurity fs = File.GetAccessControl(fileName); 
fs.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.Delete, AccessControlType.Allow)); 
File.SetAccessControl(fileName, fs);

你可以尝试以下几种方法:

1、在删除文件之前,先检查文件的属性是否包含只读,如果是的话,用File.SetAttributes方法将其改为正常属性。
2、在删除文件夹之前,先遍历删除文件夹内的所有文件和子文件夹,然后再用Directory.Delete方法删除文件夹。
3、在删除文件之前,用File.GetAccessControl方法获取文件的访问控制,然后用FileSecurity.SetOwner和FileSecurity.SetAccessRule方法为当前用户赋予完全控制的权限,最后用File.SetAccessControl方法更新文件的访问控制。

下面写了一些代码,你可以参考一下:
方法一:删除只读文件

//假设FFName是你要删除的文件的路径
if (File.GetAttributes (FFName).ToString ().IndexOf ("ReadOnly") != -1)
    File.SetAttributes (FFName, FileAttributes.Normal); //将文件属性改为正常
File.Delete (FFName); //删除文件

方法二:删除只读文件夹

//假设info是你要删除的文件夹的DirectoryInfo对象
public void DeleteFileByDirectory (DirectoryInfo info)
{
    foreach (FileInfo file in info.GetFiles ()) //遍历文件夹内的所有文件
    {
        if (file.Attributes.ToString ().IndexOf ("ReadOnly") != -1)
            file.Attributes = FileAttributes.Normal; //将文件属性改为正常
        file.Delete (); //删除文件
    }
    foreach (DirectoryInfo dir in info.GetDirectories ()) //遍历文件夹内的所有子文件夹
    {
        DeleteFileByDirectory (dir); //递归调用
    }
    info.Delete (); //删除文件夹
}

方法三:修改文件的访问控制

//假设filePath是你要删除的文件的路径
//获取文件信息
FileInfo fileInfo = new FileInfo (filePath);
//获得该文件的访问权限
System.Security.AccessControl.FileSecurity fileSecurity = fileInfo.GetAccessControl ();
//添加ereryone用户组的访问权限规则 完全控制权限
fileSecurity.AddAccessRule (new FileSystemAccessRule ("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
//添加Users用户组的访问权限规则 完全控制权限
fileSecurity.AddAccessRule (new FileSystemAccessRule ("Users", FileSystemRights.FullControl, AccessControlType.Allow));
//设置访问权限
fileInfo.SetAccessControl (fileSecurity);
//删除文件
File.Delete (filePath);

你在代码中尝试了正确的方法,但由于系统文件的限制,它可能不能正常工作。如果文件是系统文件,则需要管理员权限才能删除。如果你想继续尝试,请尝试以下java代码:

using System.Diagnostics;



ProcessStartInfo startInfo = new ProcessStartInfo();

startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = @"C:\Program Files\Common Files\microsoft shared\ink";
startInfo.FileName = "cmd.exe";
startInfo.Verb = "runas";
startInfo.Arguments = "/c del TabTip.exe";

try
{
    using (Process exeProcess = Process.Start(startInfo))
    {
        exeProcess.WaitForExit();
    }
}
catch (Exception ex)
{
    MessageBox.Show("Error deleting file: " + ex.Message);
}```

```
这段代码将启动一个命令提示符,并以管理员身份运行删除文件的命令。

您好!

您在试图删除的文件位于 “C:\Program Files\Common Files\Microsoft shared\ink” 目录,这是一个 Windows 系统目录,并且该文件是一个由系统提供的文件,因此在删除前,您需要确保您有权限进行删除操作。

一个可行的方法是使用管理员身份运行您的应用程序。您可以在 Visual Studio 中右键单击您的项目,然后选择 “以管理员身份运行” 来实现这一点。

另一个解决方案是在代码中请求管理员身份。您可以更改您的应用程序的部署方案,使其请求管理员身份,然后使用以下代码来删除文件:

File.Delete("C:\\Program Files\\Common Files\\microsoft shared\\ink\\TabTip.exe");

你可以使用File.SetAccessControl()方法来设置文件的访问权限,并使用FileSystemRights枚举来设置文件的删除权限。例如:File.SetAccessControl(fileName, new FileSecurity(fileName, FileSystemRights.Delete));

using System;
using System.IO;
using System.Security.AccessControl;

namespace GetDeletePermission
{
    class Program
    {
        static void Main(string[] args)
        {
            // 获取 C 盘根目录的文件夹的删除权限
            DirectoryInfo di = new DirectoryInfo(@"C:\");
            DirectorySecurity ds = di.GetAccessControl();

            Console.WriteLine("C盘根目录的文件夹的删除权限:");
            foreach (FileSystemAccessRule rule in ds.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
            {
                if (rule.FileSystemRights == FileSystemRights.Delete)
                {
                    Console.WriteLine("Principal: {0}", rule.IdentityReference);
                    Console.WriteLine("Access Control Type: {0}", rule.AccessControlType);
                }
            }

            Console.WriteLine();

            // 获取 C 盘根目录的文件的删除权限
            FileInfo fi = new FileInfo(@"C:\test.txt");
            FileSecurity fs = fi.GetAccessControl();

            Console.WriteLine("C盘根目录的文件的删除权限:");
            foreach (FileSystemAccessRule rule in fs.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
            {
                if (rule.FileSystemRights == FileSystemRights.Delete)
                {
                    Console.WriteLine("Principal: {0}", rule.IdentityReference);
                    Console.WriteLine("Access Control Type: {0}", rule.AccessControlType);
                }
            }

            Console.
ReadLine();
        }
    }
}


:这是一个权限问题,你需要以管理员身份运行你的程序,这样就可以获得足够的权限来删除文件。另外,你也可以尝试使用Windows API函数DeleteFile来删除文件,这样可以避免权限问题。

你所遇到的错误信息是由于文件受到操作系统的保护。在Windows中,C:\Program Files目录及其子目录中的一些文件具有较高的权限,只能由系统管理员访问。

要使用C#代码删除文件,你需要以管理员身份运行你的应用程序。你可以通过右击应用程序的可执行文件并选择 "以管理员身份运行 "来做到这一点。如果你的应用程序是作为Windows服务安装的,你可以在服务属性中设置服务以管理员身份运行。

另一种通过代码获得文件删除权限的方法是使用PInvoke方法。你可以使用kernel32.dll库中的MoveFileEx函数,以管理权限删除文件。下面是一个如何在C#中使用这个方法的例子。

using System;
using System.Runtime.InteropServices;

class Program
{
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, int dwFlags);

    static void Main(string[] args)
    {
        string filePath = @"C:\Program Files\Common Files\microsoft shared\ink\TabTip.exe";
        if (MoveFileEx(filePath, null, 0x2 | 0x1))
        {
            Console.WriteLine("File was deleted successfully");
        }
        else
        {
            Console.WriteLine("Failed to delete file: " + Marshal.GetLastWin32Error());
        }
    }
}


注意,使用这种方法需要对互操作和PInvoke有更深入的了解,在生产中使用这种方法时应该谨慎。

您可以使用以下代码以管理员身份运行您的应用程序,以便删除该文件:

using System;
using System.Diagnostics;
using System.IO;

namespace DeleteFileAsAdmin
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"C:\Program Files\Common Files\microsoft shared\ink\TabTip.exe";

            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.UseShellExecute = true;
            startInfo.WorkingDirectory = Environment.CurrentDirectory;
            startInfo.FileName = System.Reflection.Assembly.GetExecutingAssembly().Location;
            startInfo.Verb = "runas";

            try
            {
                using (Process exeProcess = Process.Start(startInfo))
                {
                    File.Delete(filePath);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error deleting file: " + ex.Message);
            }
        }
    }
}
在这个代码中,我们使用了ProcessStartInfo类来创建一个新的进程。我们使用UseShellExecute属性为该进程指定了一个布尔值,表示是否使用操作系统的默认Shell。我们也使用了Verb属性来指定该进程以管理员身份运行。在启动新的进程后,我们使用File.Delete方法来删除文件。

请注意,在管理员身份运行的程序中删除系统文件是有风险的,请谨慎使用

望采纳谢谢

你可以使用File.GetAccessControl()方法来获取文件的访问控制列表,然后使用FileSystemAccessRule类来设置文件的访问权限,最后使用File.SetAccessControl()方法来更新文件的访问控制列表,这样就可以获取文件的删除权限了。

你可以使用C语言中的chmod函数来获取文件的删除权限。chmod函数可以接受一个参数,用于指定文件的权限,其中0代表拥有删除权限。例如,如果你想要给文件“test.txt”设置删除权限,你可以使用以下代码:chmod("test.txt", 0);

如果使用普通用户身份运行代码,删除系统文件是不可以的,因为系统文件有高权限保护,只有管理员才能修改或删除。

你可以以管理员身份运行代码来解决此问题,也可以在代码中请求管理员权限:


using System.Security.Principal;

...

private static void DeleteFileWithAdminRights(string filePath)
{
    WindowsIdentity identity = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(identity);
    if (principal.IsInRole(WindowsBuiltInRole.Administrator))
    {
        // 已经以管理员身份运行,可以直接删除文件
        File.Delete(filePath);
    }
    else
    {
        // 以管理员身份重新启动当前应用程序
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.UseShellExecute = true;
        startInfo.WorkingDirectory = Environment.CurrentDirectory;
        startInfo.FileName = Application.ExecutablePath;
        startInfo.Verb = "runas";
        try
        {
            Process.Start(startInfo);
        }
        catch (System.ComponentModel.Win32Exception)
        {
            // 用户取消了请求
        }
    }
}

在以管理员身份运行的情况下,您可以通过以上代码删除文件