获取 System.InvalidOperationException: '获取文件所有权时集合已修改错误



在制作以管理员用户身份执行的应用程序的过程中。如果所述文件存在于C:\上的某些位置,则应用程序会复制并覆盖文件。如果管理员无权对所请求的文件执行操作,则该应用程序将获得所有权并将完全控制权限分配给管理员用户,以便他们可以覆盖所述文件。

然而,当它尝试这样做时,我得到了以下错误:

System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.' 

我读到Foreach循环在迭代过程中不能修改。所以我将代码转换为使用For循环,但问题仍然存在!我花了很多时间试图将其付诸实践和研究,但我最终还是陷入了困境,任何帮助都将不胜感激。以下是我的代码:


string[] lines = File.ReadAllLines(@"C:Temp2BarsInstallerFilesToInstall.txt");
string sourcePath = @"C:Temp2BarsInstaller";
for (int i = 0; i <= lines.Length; i++)
{

string[] col = lines[i].Split('=');
string fileName = col[0];
string pathName = col[1];

string fullDestPath = pathName + fileName;
string fileCopyToLocation = pathName;
string fulleSourcePath = sourcePath + fileName;

copyFilesToInstall(fulleSourcePath, fullDestPath, fileCopyToLocation);
}
void copyFilesToInstall(string sourceFile, string destFile, string target)
{
if (Directory.Exists(target) == false)
{
Directory.CreateDirectory(target);
}
//1 check if we have permissions to overrite the file or copy file to directory
//if we dont then give us permisison
string fileName = destFile;
Console.WriteLine("Adding access control entry for "
+ fileName);

// Get a FileSecurity object that represents the
// current security settings.
if (File.Exists(destFile))
{
FileSecurity fSecurity = File.GetAccessControl(destFile);
// Add the FileSystemAccessRule to the security settings.
fSecurity.AddAccessRule(new FileSystemAccessRule(WindowsIdentity.GetCurrent().User,
FileSystemRights.FullControl, AccessControlType.Allow));
fSecurity.SetOwner(WindowsIdentity.GetCurrent().User);
using (new ProcessPrivileges.PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.TakeOwnership))
{
fSecurity.SetOwner(WindowsIdentity.GetCurrent().User); //ERROR OCCURS HERE
}

// Set the new access settings.
File.SetAccessControl(destFile, fSecurity);         
}

}

全堆栈跟踪

at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)rn   
at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()rn   
at ProcessPrivileges.PrivilegeEnabler.InternalDispose() 
in C:\Users\bazile\source\repos\ProcessPrivileges\src\ProcessPrivileges.Shared\PrivilegeEnabler.cs:line 191rn   
at ProcessPrivileges.PrivilegeEnabler.Dispose() in C:\Users\bazile\source\repos\ProcessPrivileges\src\ProcessPrivileges.Shared\PrivilegeEnabler.cs:line 149rn  
at BarsInstaller.Form1.copyFilesToInstall(String sourceFile, String destFile, String target) in D:\SourceControl\BarsInstaller\BarsInstaller\Form1.cs:line 224

在@OguzOzgul的帮助下,我现在已经解决了这个问题,问题是我使用的Nuget包有一个1.5.7版本的错误,所以我从这个网站下载了源代码:https://archive.codeplex.com/?p=processprivileges构建了它并添加了DLL作为引用,这个错误现在已经消失了。

最新更新