在制作一个应用程序的过程中,该应用程序会以管理员用户的身份执行。如果文件存在于C:\\上的某些位置,该应用程序将复制和覆盖文件,如果管理员没有权限对请求的文件进行操作,那么该应用程序将拥有所有权,并将完全控制权限分配给管理员用户,以便他们可以覆盖所述文件。
然而,当我试图这样做时,我得到了以下错误。
System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'
我读到Foreach循环在迭代过程中不能被修改。 所以我把我的代码转换为使用For循环,但问题仍然存在!我花了很多时间试图解决这个问题。我已经花了很多时间试图让这个工作和研究,但我最终还是在兜圈子,任何帮助将是感激的。 以下是我的代码。
string[] lines = File.ReadAllLines(@"C:\Temp2\BarsInstaller\FilesToInstall.txt");
string sourcePath = @"C:\Temp2\BarsInstaller\";
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)\r\n
at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()\r\n
at ProcessPrivileges.PrivilegeEnabler.InternalDispose()
in C:\\Users\\bazile\\source\\repos\\ProcessPrivileges\\src\\ProcessPrivileges.Shared\\PrivilegeEnabler.cs:line 191\r\n
at ProcessPrivileges.PrivilegeEnabler.Dispose() in C:\\Users\\bazile\\source\\repos\\ProcessPrivileges\\src\\ProcessPrivileges.Shared\\PrivilegeEnabler.cs:line 149\r\n
at BarsInstaller.Form1.copyFilesToInstall(String sourceFile, String destFile, String target) in D:\\SourceControl\\BarsInstaller\\BarsInstaller\\Form1.cs:line 224
我现在已经在@OguzOzgul的帮助下解决了这个问题,问题是我使用的Nuget包有一个1.5.7版本的bug,所以我从这个网站下载了源代码。https:/archive.codeplex.com?p=processprivileges 并添加DLL作为参考,现在这个错误已经消失了。