Мне нужно добавить информацию о папке из поиска в документ PDF, но на данный момент она отображает только одну найденную папку, а не остальные.
Приложение экспортирует данные в файл .csv
иЯ хотел бы экспортировать в PDF, а также.
Это код, который я сейчас использую:
private void bgWorker_Scan_DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(1500); // Sleep to stop panel flicker on shorter audits (< 1s)
directorySearch(auditLocation, exportLocation, showSystemAccounts, 1);
}
private void bgWorker_Scan_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
DateTime dt = DateTime.Now;
ucProgress.changeScanProgressDisplay(true);
ucAudit.displayError("Scan Completed -> " + foldersScanned + " folders audited.", false);
// Add finished audit information to the logfile
log.addToPermissionsLogFile(System.Environment.NewLine + System.Environment.NewLine + System.Environment.NewLine);
log.addToPermissionsLogFile("Folders Scanned: " + foldersScanned + " | Folders with access errors (can not scan deeper): " + foldersAccessErrors);
log.addToPermissionsLogFile("Date/Time log completed:" + dt.ToString("HH:mm:ss dd/MM/yy"));
if (foldersAccessErrors > 0)
{
log.addToPermissionsLogFile(System.Environment.NewLine);
}
}
// This function is where directories are recursively audited
private void directorySearch(string location, string exportLocation, bool showSystemAccounts, int currentLevel)
{
if (currentLevel > numLevelsDeepSetting)
{
// Reached levels limit so do not continue
}
else
{
List<string> dirs = new List<string>();
try
{
foreach (string dir in Directory.GetDirectories(location))
{
foldersCounted++;
dirs.Add(dir);
}
}
catch (Exception e)
{
// Suppress error because you want the audit scan to continue
foldersAccessErrors++;
}
foreach (string dir in dirs)
{
currentFolder = dir;
foldersScanned++;
try
{
List<string> logListCSV = new List<string>();
DirectoryInfo di = new DirectoryInfo(dir);
var permissions = di.Attributes;
string csvDir = dir;
string csvPermissions = "";
DirectorySecurity dSecurity = Directory.GetAccessControl(dir);
foreach (FileSystemAccessRule rule in dSecurity.GetAccessRules(true, true, typeof(NTAccount)))
{
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "AD User Report.pdf");
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create, FileAccess.Write));
document.Open();
PdfPTable header = new PdfPTable(1);
header.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
header.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
header.AddCell(iTextSharp.text.Image.GetInstance(@"C:\Users\Dev\Pictures\images\user_report.png"));
document.Add(header);
document.Add(new Paragraph(csvDir.ToString()));
document.Add(new Paragraph(csvPermissions.ToString()));
document.Close();
if
(
!rule.FileSystemRights.ToString().Contains("268435456") &&
!rule.FileSystemRights.ToString().Contains("-536805376") &&
!rule.FileSystemRights.ToString().Contains("-1610612736")
)
{
if (showSystemAccounts)
{
string csvFormat = rule.IdentityReference + " [" + rule.AccessControlType + ": " + rule.FileSystemRights + "]";
string csvSantised = csvFormat.Replace(",", " ");
csvPermissions += ", " + csvSantised;
}
else
{
// Check results do not show system accounts
if (!rule.IdentityReference.ToString().Contains("BUILTIN") &&
!rule.IdentityReference.ToString().Contains(@"NT AUTHORITY\SYSTEM"))
{
string csvFormat = rule.IdentityReference + " [" + rule.AccessControlType + ": " + rule.FileSystemRights + "]";
string csvSantised = csvFormat.Replace(",", " ");
csvPermissions += ", " + csvSantised;
}
}
}
}
// Update status on Progress User Control
ucProgress.Invoke(new System.Windows.Forms.MethodInvoker(delegate
{
ucProgress.setProgressMessage(foldersScanned + " folders scanned");
}));
// Add string to List<string>
//logListCSV.Add(csvDir + ", " + csvPermissions);
logListCSV.Add(csvDir + csvPermissions + ", ");
// Add List<string> to logfile function
log.addListToPermissionsLogFile(logListCSV);
}
catch (Exception e)
{
foldersAccessErrors++;
log.addToPermissionsLogFile(" -----------------> Error accessing directory. " + e);
continue;
}
// Keep recursive search going!
directorySearch(dir, exportLocation, showSystemAccounts, currentLevel + 1);
}
Документ PDF генерируется правильно, однако он отображает только первую строку папки и поиск разрешений.В файле .csv
отображаются все найденные папки и права доступа к этой папке.
Конечно, это не должно иметь большого значения для создания PDF?
Спасибо
РЕДАКТИРОВАТЬ
Я решил проблему, но теперь мне нужно добавить новую строку после ,
в документе, отображающем разрешения
Воткод, который я использую:
if (currentLevel > numLevelsDeepSetting)
{
// Reached levels limit so do not continue
}
else
{
List<string> dirf = new List<string>();
try
{
foreach (string dirfo in Directory.GetDirectories(location))
{
foldersCounted++;
document.Add(new Paragraph(dirfo.ToString()));
document.Add(new Paragraph(csvPermissions.ToString()));
}
}
catch (Exception e)
{
// Suppress error because you want the audit scan to continue
foldersAccessErrors++;
}
document.Close();
}
Итак, где document.Add(new Paragraph(csvPermissions.ToString()));
показывает мне пользователей в одной строке, разделенных ,
.Я хотел бы, чтобы это показывало каждого пользователя в отдельной строке, если это возможно?