private static void ProcessDocFile(Order order, string filePath) { ShellPropertyCollection fileProperties = new ShellPropertyCollection(filePath); foreach (var property in fileProperties) { switch (property.CanonicalName) { case "System.Company": string company = property.ValueAsObject?.ToString(); order.NoticeCompany = company; break; case "System.Title": string title = property.ValueAsObject?.ToString(); order.NoticeSubject = title; break; case "System.Subject": string subject = property.ValueAsObject?.ToString(); order.NoticeSubject = subject; break; case "System.Author": if (property.ValueAsObject is string[] authors) { string authorsString = string.Join(", ", authors); order.NoticeCreator = authorsString; } break; case "System.Document.Template": string template = property.ValueAsObject?.ToString(); order.NoticeTemplate = template; break; case "System.Document.LastAuthor": string lastAuthor = property.ValueAsObject?.ToString(); order.NoticeLastAuthor = lastAuthor; break; case "System.Document.DatePrinted": string datePrinted = property.ValueAsObject?.ToString(); order.NoticeDatePrinted = datePrinted; break; case "System.Document.DateCreated": string dateCreated = property.ValueAsObject?.ToString(); order.NoticeDateCreated = dateCreated; break; case "System.Document.DateSaved": string dateSaved = property.ValueAsObject?.ToString(); order.NoticeDateSaved = dateSaved; break; } } }
public static void GetFilmDetails(this FileInfo movieFile) { using (ShellPropertyCollection properties = new ShellPropertyCollection(movieFile.FullName)) { foreach (IShellProperty prop in properties) { string value = (prop.ValueAsObject == null) ? "" : prop.FormatForDisplay(PropertyDescriptionFormatOptions.None); Console.WriteLine("{0} = {1}", prop.CanonicalName, value); } } }
public static string GetFilmDetails(this FileInfo movieFile) { using (ShellPropertyCollection properties = new ShellPropertyCollection(movieFile.FullName)) { StringBuilder sb = new StringBuilder(); foreach (IShellProperty prop in properties) { string value = (prop.ValueAsObject == null) ? "" : prop.FormatForDisplay(PropertyDescriptionFormatOptions.None); sb.AppendLine($"{prop.CanonicalName} = {value}"); } return(sb.ToString()); } }
private static void EnumProperties(string fileName, string filter) { ShellPropertyCollection collection = new ShellPropertyCollection(fileName); var properties = collection .Where( prop => prop.CanonicalName != null && (filter == null ? true : prop.CanonicalName.StartsWith(filter, StringComparison.CurrentCultureIgnoreCase))) .ToArray(); Array.ForEach( properties, p => { DisplayPropertyValue(p); }); }
private void saveFileButton_Click(object sender, EventArgs e) { // Initialize detailsListView.Items.Clear(); pictureBox1.Image = null; // Show a CommonSaveFileDialog with couple of file filters. // Also show some properties (specific to the filter selected) // that the user can update from the dialog itself. CommonSaveFileDialog saveCFD = new CommonSaveFileDialog(); saveCFD.AlwaysAppendDefaultExtension = true; saveCFD.DefaultExtension = ".docx"; // When the file type changes, we will add the specific properties // to be collected from the dialog (refer to the saveCFD_FileTypeChanged event handler) saveCFD.FileTypeChanged += new EventHandler(saveCFD_FileTypeChanged); saveCFD.Filters.Add(new CommonFileDialogFilter("Word Documents", "*.docx")); saveCFD.Filters.Add(new CommonFileDialogFilter("JPEG Files", "*.jpg")); if (saveCFD.ShowDialog() == CommonFileDialogResult.Ok) { // Get the selected file (this is what we'll save...) // Save it to disk, so we can read/write properties for it // Because we can't really create a Office file or Picture file, just copying // an existing file to show the properties if (saveCFD.SelectedFileTypeIndex == 1) { File.Copy(Path.Combine(Directory.GetCurrentDirectory(), "sample files\\test.docx"), saveCFD.FileName, true); } else { File.Copy(Path.Combine(Directory.GetCurrentDirectory(), "sample files\\test.jpg"), saveCFD.FileName, true); } // Get the ShellObject for this file ShellObject selectedSO = ShellFile.FromFilePath(saveCFD.FileName); // Get the properties from the dialog (user might have updated the properties) ShellPropertyCollection propColl = saveCFD.CollectedProperties; // Write the properties on our shell object using (ShellPropertyWriter propertyWriter = selectedSO.Properties.GetPropertyWriter()) { if (propColl.Contains(SystemProperties.System.Title)) { propertyWriter.WriteProperty(SystemProperties.System.Title, propColl[SystemProperties.System.Title].ValueAsObject); } if (propColl.Contains(SystemProperties.System.Author)) { propertyWriter.WriteProperty(SystemProperties.System.Author, propColl[SystemProperties.System.Author].ValueAsObject); } if (propColl.Contains(SystemProperties.System.Keywords)) { propertyWriter.WriteProperty(SystemProperties.System.Keywords, propColl[SystemProperties.System.Keywords].ValueAsObject); } if (propColl.Contains(SystemProperties.System.Comment)) { propertyWriter.WriteProperty(SystemProperties.System.Comment, propColl[SystemProperties.System.Comment].ValueAsObject); } if (propColl.Contains(SystemProperties.System.Category)) { propertyWriter.WriteProperty(SystemProperties.System.Category, propColl[SystemProperties.System.Category].ValueAsObject); } if (propColl.Contains(SystemProperties.System.ContentStatus)) { propertyWriter.WriteProperty(SystemProperties.System.Title, propColl[SystemProperties.System.Title].ValueAsObject); } if (propColl.Contains(SystemProperties.System.Photo.DateTaken)) { propertyWriter.WriteProperty(SystemProperties.System.Photo.DateTaken, propColl[SystemProperties.System.Photo.DateTaken].ValueAsObject); } if (propColl.Contains(SystemProperties.System.Photo.CameraModel)) { propertyWriter.WriteProperty(SystemProperties.System.Photo.CameraModel, propColl[SystemProperties.System.Photo.CameraModel].ValueAsObject); } if (propColl.Contains(SystemProperties.System.Rating)) { propertyWriter.WriteProperty(SystemProperties.System.Rating, propColl[SystemProperties.System.Rating].ValueAsObject); } } currentlySelected = selectedSO; DisplayProperties(selectedSO); showChildItemsButton.Enabled = selectedSO is ShellContainer ? true : false; } }
private static void EnumProperties(string fileName, string filter) { ShellPropertyCollection collection = new ShellPropertyCollection(fileName); var properties = collection .Where( prop => prop.CanonicalName != null && (filter == null ? true : prop.CanonicalName.StartsWith(filter, StringComparison.CurrentCultureIgnoreCase))) .ToArray(); Array.ForEach( properties, p=> { DisplayPropertyValue(p); }); }
public static string ReadTreatmentsDetailsFileContent(string file, string sheetName, out string fileInfo, BackgroundWorker bw = null) { fileInfo = "Unavailable"; Logging.ToLog("Подготовка таблицы для записи считанных данных"); FileContentTreatmentsDetails = new DataTable(); foreach (Header header in headers) { FileContentTreatmentsDetails.Columns.Add(header.DbField, header.FieldType); } DataTable dataTable = ExcelReader.ReadExcelFile(file, sheetName); int minColumnQuantity = headers.Count; if (dataTable.Columns.Count < minColumnQuantity) { string message = "Кол-во столбцов в файле меньше " + minColumnQuantity + ", пропуск обработки"; filesToImport[file] = message; Logging.ToLog(file); return(message); } int firstDataRow = GetFirstDataRowTreatmentsDetails(dataTable, out string columnError); if (firstDataRow == -1) { string message = "Формат файла не соответствует заданному шаблону / не удалось найти строку с заголовками"; if (!string.IsNullOrEmpty(columnError)) { message += "; Не удалось найти столбец: '" + columnError + "'"; } filesToImport[file] = message; Logging.ToLog(message); return(message); } string msg = "Считывание свойств файла"; Logging.ToLog(msg); if (bw != null) { bw.ReportProgress(0, msg); } try { ShellPropertyCollection properties = new ShellPropertyCollection(file); string lastAuthor = properties["System.Document.LastAuthor"].ValueAsObject.ToString(); string dateSaved = properties["System.Document.DateSaved"].ValueAsObject.ToString(); string computerName = properties["System.ComputerName"].ValueAsObject.ToString(); fileInfo = Path.GetFileName(file) + "@" + lastAuthor + "@" + dateSaved + "@" + computerName; } catch (Exception e) { Logging.ToLog(e.Message + Environment.NewLine + e.StackTrace); } msg = "Строка, содержащая заголовки: " + (firstDataRow + 1); Logging.ToLog(msg); if (bw != null) { bw.ReportProgress(0, msg); } msg = "Разбор содержимого строк"; Logging.ToLog(msg); if (bw != null) { bw.ReportProgress(0, msg); } int errorCounter = 0; for (int i = firstDataRow + 1; i < dataTable.Rows.Count; i++) { try { ParseRow(dataTable.Rows[i]); } catch (Exception e) { if (bw != null) { bw.ReportProgress(0, "Строка: " + (i + 1) + ", " + e.Message); } errorCounter++; } } string fileResult = "Считано строк: " + FileContentTreatmentsDetails.Rows.Count + ", ошибок: " + errorCounter; Logging.ToLog(fileResult); return(fileResult); }
public static string ReadProfitAndLossLFileContent(string file, string sheetName, out string fileInfo, BackgroundWorker bw = null) { fileInfo = "Unavailable"; DataTable dataTable = ExcelReader.ReadExcelFile(file, sheetName); if (dataTable == null || dataTable.Rows.Count == 0) { string message = "Не удалось считать файл / нет данных"; filesToImport[file] = message; Logging.ToLog(message); return(message); } string msg = "Считывание свойств файла"; Logging.ToLog(msg); if (bw != null) { bw.ReportProgress(0, msg); } try { ShellPropertyCollection properties = new ShellPropertyCollection(file); string lastAuthor = properties["System.Document.LastAuthor"].ValueAsObject.ToString(); string dateSaved = properties["System.Document.DateSaved"].ValueAsObject.ToString(); string computerName = properties["System.ComputerName"].ValueAsObject.ToString(); fileInfo = Path.GetFileName(file) + "@" + lastAuthor + "@" + dateSaved + "@" + computerName; } catch (Exception e) { Logging.ToLog(e.Message + Environment.NewLine + e.StackTrace); } msg = "Разбор содержимого строк"; Logging.ToLog(msg); if (bw != null) { bw.ReportProgress(0, msg); } int errorCounter = 0; int hasDataRow = 0; int quarterRow = 1; int objectNameRow = 2; int dateRow = 3; int firstDataRow = 4; int firstDataColumn = 3; if (dataTable.Rows.Count < firstDataRow + 1) { msg = "Формат таблицы не соответствует ожидаемому (кол-во строк меньше необходимого - " + (firstDataRow + 1) + ")"; Logging.ToLog(msg); if (bw != null) { bw.ReportProgress(0, msg); } return(msg); } msg = "Считывание строки, содержащей даты"; Logging.ToLog(msg); if (bw != null) { bw.ReportProgress(0, msg); } int year = -1; DataRow dataRowDates = dataTable.Rows[dateRow]; List <string> dates = new List <string>(); foreach (object item in dataRowDates.ItemArray) { if (item == null || string.IsNullOrEmpty(item.ToString()) || string.IsNullOrWhiteSpace(item.ToString())) { dates.Add(string.Empty); continue; } if (double.TryParse(item.ToString(), out double result)) { if (result > 2000 && result < 2030) { dates.Add(item.ToString()); if (year == -1) { year = (int)result; } } else { try { DateTime dt = DateTime.FromOADate(result); dates.Add(months[dt.Month]); if (year == -1) { year = dt.Year; } } catch (Exception exc) { dates.Add(string.Empty); Logging.ToLog(exc.Message + Environment.NewLine + exc.StackTrace); } } } else { if (DateTime.TryParse(item.ToString(), out DateTime dt)) { dates.Add(months[dt.Month]); if (year == -1) { year = dt.Year; } } else { dates.Add(item.ToString()); } } } if (year == -1) { msg = "Не удалось определить год в загруженном файле, поиск по строке: " + (dateRow + 1); Logging.ToLog(msg); if (bw != null) { bw.ReportProgress(0, msg); } return(msg); } string groupNameLevel1 = null; string groupNameLevel2 = null; for (int i = firstDataRow; i < dataTable.Rows.Count; i++) { msg = "Строка: " + (i + 1) + " / " + dataTable.Rows.Count; Logging.ToLog(msg); if (bw != null) { bw.ReportProgress(0, msg); } DataRow dataRow = dataTable.Rows[i]; try { string rowGroupNameLevel1 = dataRow[0].ToString(); string rowGroupNameLevel2 = dataRow[1].ToString(); string rowGroupNameLevel3 = dataRow[2].ToString(); string rowGroupNameTotal = rowGroupNameLevel1 + rowGroupNameLevel2 + rowGroupNameLevel3; if (string.IsNullOrEmpty(rowGroupNameTotal) || string.IsNullOrWhiteSpace(rowGroupNameTotal)) { msg = "Отсуютствую заголовки групп, пропуск"; Logging.ToLog(msg); if (bw != null) { bw.ReportProgress(0, msg); } groupNameLevel1 = null; groupNameLevel2 = null; continue; } if (string.IsNullOrEmpty(rowGroupNameLevel3) || string.IsNullOrWhiteSpace(rowGroupNameLevel3)) { rowGroupNameLevel3 = null; } if (!string.IsNullOrEmpty(rowGroupNameLevel1) && !string.IsNullOrWhiteSpace(rowGroupNameLevel1)) { groupNameLevel1 = rowGroupNameLevel1; groupNameLevel2 = null; } if (!string.IsNullOrEmpty(rowGroupNameLevel2) || !string.IsNullOrWhiteSpace(rowGroupNameLevel2)) { groupNameLevel2 = rowGroupNameLevel2; } for (int x = firstDataColumn; x < dataRow.ItemArray.Length; x++) { if (dataRow[x] == null || string.IsNullOrEmpty(dataRow[x].ToString()) || string.IsNullOrWhiteSpace(dataRow[x].ToString())) { continue; } string objectName = dataTable.Rows[objectNameRow][x].ToString(); if (string.IsNullOrEmpty(objectName) || string.IsNullOrWhiteSpace(objectName)) { if (string.IsNullOrEmpty(dates[x])) { continue; } else { objectName = "Не указано"; } } if (double.TryParse(dataRow[x].ToString(), out double result)) { ItemProfitAndLoss item = new ItemProfitAndLoss { ObjectName = dataTable.Rows[objectNameRow][x].ToString(), PeriodYear = year, PeriodType = dates[x], GroupNameLevel1 = groupNameLevel1, GroupNameLevel2 = groupNameLevel2, GroupNameLevel3 = rowGroupNameLevel3, Value = result, GroupSortingOrder = i + 1, ObjectSrotingOrder = x + 1 }; string quarter = dataTable.Rows[quarterRow][x].ToString(); if (int.TryParse(quarter, out int resultQuarter)) { if (resultQuarter != 0) { item.Quarter = resultQuarter; } } string hasData = dataTable.Rows[hasDataRow][x].ToString(); if (int.TryParse(hasData, out int resultHasData)) { if (!string.IsNullOrEmpty(hasData) && !string.IsNullOrWhiteSpace(hasData)) { item.HasData = resultHasData == 4; } } FileContentProfitAndLoss.Add(item); } else { msg = "Не удалось преобразовать в число значение в столбце " + (x + 1) + " - '" + dataRow[x] + "'"; Logging.ToLog(msg); if (bw != null) { bw.ReportProgress(0, msg); } errorCounter++; continue; } } } catch (Exception e) { if (bw != null) { bw.ReportProgress(0, "Строка: " + (i + 1) + ", " + e.Message); } errorCounter++; } } string fileResult = "Считано объектов: " + FileContentProfitAndLoss.Count + ", ошибок: " + errorCounter; Logging.ToLog(fileResult); return(fileResult); }
private void ShowSelectedImage(bool force = false) { #region detect selection items is same or not if (!force && lastSelections.Count == explorerBrowser.SelectedItems.Count) { bool diff = false; foreach (ShellObject item in explorerBrowser.SelectedItems) { if (!item.IsFileSystemObject || item.IsLink) { continue; } //if ( !lastSelections.Contains( item.ParsingName ) ) string dp = item.ParsingName; string ext = Path.GetExtension(dp); if (File.GetAttributes(dp).HasFlag(FileAttributes.Directory)) { continue; } if (EXIF.PhotoExts.Contains(ext, StringComparer.CurrentCultureIgnoreCase)) { if (!lastSelections.Contains(item.Name)) { diff = true; selection_changed = true; break; } } } if (!diff) { selection_changed = false; return; } } else { selection_changed = true; } #endregion BeginInvoke(new MethodInvoker(delegate() { #region get properties if (!force && !selection_changed) { return; } tsFilesSelected.Text = $"Selected: 0"; selection_changed = false; List <KeyValuePair <Image, string> > imgs = new List <KeyValuePair <Image, string> >(); try { lastSelections.Clear(); foreach (ShellObject item in explorerBrowser.SelectedItems) { if (!item.IsFileSystemObject || item.IsLink) { continue; } if (lastSelections.Contains(item.Name)) { continue; } #region get property string dn = item.Name; string dp = item.ParsingName; string ext = Path.GetExtension(dp); if (!File.GetAttributes(dp).HasFlag(FileAttributes.Directory)) { if (EXIF.PhotoExts.Contains(ext, StringComparer.CurrentCultureIgnoreCase)) { lastSelections.Add(item.Name); Image thumb = new Bitmap(item.Thumbnail.MediumBitmap); ShellPropertyCollection props = item.Properties.DefaultPropertyCollection; Dictionary <string, string> properties = new Dictionary <string, string>(); //if (props.Contains( "System.Artist" )) //{ //} for (int i = 0; i < props.Count; i++) { if (props[i].CanonicalName == null) { continue; } string key = props[i].CanonicalName.Replace("System.", ""); string value = ""; //if ( !key.StartsWith( "Date" ) && !key.StartsWith( "Photo.Date" ) && !key.StartsWith( "ItemPathDisplay" ) ) continue; if (!key.StartsWith("Photo.Date") && !key.StartsWith("ItemPathDisplay")) { continue; } object objValue = props[i].ValueAsObject; //object objValue = new object(); //continue; if (objValue != null) { if (props[i].ValueType == typeof(string[])) { value = string.Join(" ; ", (string[])objValue); } else if (props[i].ValueType == typeof(uint[])) { value = string.Join(" , ", (uint[])objValue); } else if (props[i].ValueType == typeof(double[])) { value = string.Join(" , ", (double[])objValue); } else { value = objValue.ToString(); } } properties.Add(key, value); } //properties.Add( "Artist", properties.ContainsKey( "Author" ) ? properties["Author"] : "" ); //properties.Add( "Copyright", properties.ContainsKey( "Copyright" ) ? properties["Copyright"] : "" ); //properties.Add( "ImageDescription", properties.ContainsKey( "Subject" ) ? properties["Subject"] : "" ); //properties.Add( "Software", properties.ContainsKey( "ApplicationName" ) ? properties["ApplicationName"] : "" ); properties.Add("FileSize", properties.ContainsKey("Size") ? properties["Size"] : ""); //properties.Add( "FileName", properties.ContainsKey( "ItemPathDisplay" ) ? properties["ItemPathDisplay"] : "" ); properties.Add("FilePath", properties.ContainsKey("ItemPathDisplay") ? properties["ItemPathDisplay"] : ""); properties.Add("FolderName", properties.ContainsKey("ItemFolderPathDisplay") ? properties["ItemFolderPathDisplay"] : ""); properties.Add("FileType", properties.ContainsKey("ItemTypeText") ? properties["ItemTypeText"] : ""); //properties.Add( "Dimensions", properties.ContainsKey( "Image.Dimensions" ) ? properties["Image.Dimensions"] : "" ); //properties.Add( "Resolution", properties.ContainsKey( "Image.HorizontalResolution" ) && properties.ContainsKey( "Image.VerticalResolution" ) ? $"{properties["Image.HorizontalResolution"]} x {properties["Image.VerticalResolution"]}" : "" ); //properties.Add( "EquipmentModel", properties.ContainsKey( "Photo.CameraModel" ) ? properties["Photo.CameraModel"] : "" ); //properties.Add( "ExposureTime", properties.ContainsKey( "Photo.ExposureTime" ) ? properties["Photo.ExposureTime"] : "" ); //properties.Add( "FNumber", properties.ContainsKey( "Photo.FNumber" ) ? properties["Photo.FNumber"] : "" ); //properties.Add( "FocalLength", properties.ContainsKey( "Photo.FocalLength" ) ? properties["Photo.FocalLength"] : "" ); //properties.Add( "ISOSpeed", properties.ContainsKey( "Photo.ISOSpeed" ) ? properties["Photo.ISOSpeed"] : "" ); //properties.Add( "ImageDescription", properties.ContainsKey( "Title" ) ? properties["Title"] : "" ); properties.Add("DateTaken", properties.ContainsKey("Photo.DateTaken") ? properties["Photo.DateTaken"] : ""); //properties.Add( "Rating", "" ); //properties.Add( "StarRating", "" ); //properties.Add( "UserComment", "" ); thumb.Tag = properties; //if ( item.Properties != null ) //{ // thumb.Tag = item.Properties.DefaultPropertyCollection; //} imgs.Add(new KeyValuePair <Image, string>(thumb, dp)); } } #endregion } } catch { }; tsFilesSelected.Text = $"Selected: {imgs.Count}"; try { if (MapViewer != null && MapViewer.Visible) { MapViewer.ShowImage(imgs); } } catch { }; #endregion })); }