2017-02-15 18 views
1

Проблема:Экспорт метаданных из пользовательской вкладки из свойств файла для списка файлов в подпапках

На моем файловом сервере Windows, у меня есть около 1000000 SolidWorks файлов, которые имеют метаданные в свойствах файла под обычаем (см. рисунок ниже), который я хотел бы экспортировать в один файл CSV.

Custom Tab image

Эти файлы находятся в суб-дереве папок, а также в смеси с другими типами файлов.

Решение:

Скрипт нужен только предназначаться для определенных типов файлов (расширения) в суб-дереве папок, что экспорт метаданных из настраиваемой вкладки в файл CSV, где я могу затем очистить и импортировать данные в базу данных SQL.

Я не уверен, что это лучший способ достичь этого. Я думал о линиях PowerShell, любая помощь, которую нужно было получить, была бы весьма признательна.

ответ

2

Если вы используете язык .NET, такой как C# или Visual Basic, вы можете использовать библиотеки SolidWorks API и библиотеки Document Manager (вам нужно будет получить лицензию, бесплатную с подпиской с портала клиентов), чтобы извлечь эту информацию без открытия файлов. Это довольно быстро. Что касается просмотра только определенных файлов, это прямо связано с .NET IO.Path.GetExtension.

Ниже приведен рабочий пример того, что, как я думаю, вы ищете.

Вам понадобится dll Document Manager, который находится на SDK SolidWorks API, который входит в установочный носитель. Затем вы можете ссылаться на SolidWorks.Interop.swdocumentmgr.dll.

Вам также понадобится серийный номер диспетчера документов, который вы можете запросить через портал клиентов SolidWorks бесплатно с подпиской SolidWorks. После того, как у вас есть это число, замените строковое значение переменной ниже на весь серийный номер в кавычках.

Чтобы определить, какие пользовательские свойства следует читать из файлов SolidWorks, просто измените свойства listToRead, чтобы включить любые значения, необходимые для извлечения. Они НЕ чувствительны к регистру.

Вы запустите это, вам будет предложено ввести путь к каталогу. Здесь также будет создан файл Output.csv.

В нижней части экрана показан образец результатов.

using SolidWorks.Interop.swdocumentmgr; 
using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Text; 

namespace WriteProperties 
{ 
    class Program 
    { 
     static ISwDMApplication4 docManager; 
     static List<string> propertiesToRead = new List<string>() { "Number", "Description", "Revision", "Material", "Finish", "Weight" }; 
     const string lic = "YOU CAN GET THIS NUMBER FROM THE CUSTOMER PORTAL WITH YOUR SOLIDWORKS SUBSCRIPTION AT NO COST"; 

     static char[] charactersToQuote = { ',', '"', '\n' }; 
     const string QUOTE = "\""; 
     const string QUOTEFORMATTED = "\"\""; 


     static void Main(string[] args) 
     { 
      string directoryPath = GetDirectory(args); 

      if (string.IsNullOrEmpty(directoryPath)) return; 

      if (!LoadDocManager()) return; 

      string outputPath = Path.Combine(directoryPath, "Output.csv"); 

      StringBuilder sb = new StringBuilder(); 
      sb.AppendLine("File Name," + string.Join(",", propertiesToRead)); 

      int counter = 0; 

      foreach (string filePath in Directory.EnumerateFiles(directoryPath, "*.sld*", SearchOption.AllDirectories)) 
      { 
       SwDMDocument21 dmDocument = GetDocument(filePath); 
       if (dmDocument == null) continue; 

       WriteProperties(sb, dmDocument, filePath); 
       counter++; 
      } 

      File.WriteAllText(outputPath, sb.ToString()); 

      Console.WriteLine("{0} files read and saved to {1}", counter, outputPath); 
      Console.ReadLine(); 
     } 

     static string GetDirectory(string[] args) 
     { 
      if (args != null && args.Count() > 0 && Directory.Exists(args[0])) return args[0]; 

      Console.WriteLine("Directory to read:"); 
      string filePath = Console.ReadLine(); 

      if (Directory.Exists(filePath)) return filePath; 

      Console.WriteLine("Directory does not exists: {0}", filePath); 
      return string.Empty; 
     } 

     static bool LoadDocManager() 
     { 
      if (docManager != null) return true; 

      try 
      { 
       SwDMClassFactory factory = new SwDMClassFactory(); 
       if (factory == null) throw new NullReferenceException(nameof(SwDMClassFactory)); 

       docManager = (SwDMApplication4)factory.GetApplication(lic); 
       if (docManager == null) throw new NullReferenceException(nameof(SwDMApplication4)); 

       return true; 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine("Document Manager failed to load: {0}", ex.Message); 
       Console.ReadLine(); 
       return false; 
      } 
     } 

     static SwDMDocument21 GetDocument(string filePath) 
     { 
      SwDmDocumentType documentType = GetDocType(filePath); 
      if (documentType == SwDmDocumentType.swDmDocumentUnknown) return null; 

      SwDmDocumentOpenError result = SwDmDocumentOpenError.swDmDocumentOpenErrorNone; 
      SwDMDocument21 dmDocument = (SwDMDocument21)docManager.GetDocument(filePath, documentType, true, out result); 

      if (result == SwDmDocumentOpenError.swDmDocumentOpenErrorNone || result == SwDmDocumentOpenError.swDmDocumentOpenErrorFileReadOnly) return dmDocument; 

      if (dmDocument != null) dmDocument.CloseDoc(); 

      return null; 
     } 

     static SwDmDocumentType GetDocType(string filePath) 
     { 
      if (filePath.Contains("~$")) return SwDmDocumentType.swDmDocumentUnknown; 

      switch (Path.GetExtension(filePath).ToLower()) 
      { 
       case ".sldprt": return SwDmDocumentType.swDmDocumentPart; 
       case ".sldasm": return SwDmDocumentType.swDmDocumentAssembly; 
       case ".slddrw": return SwDmDocumentType.swDmDocumentDrawing; 
       default: return SwDmDocumentType.swDmDocumentUnknown; 
      } 
     } 

     static void WriteProperties(StringBuilder sb, SwDMDocument21 dmDocument, string filePath) 
     { 
      Console.WriteLine("Reading {0}", filePath); 

      List<string> propertiesInFile = new List<string>(); 

      if (dmDocument.GetCustomPropertyCount() > 0) propertiesInFile.AddRange(dmDocument.GetCustomPropertyNames()); 

      string csvLine = filePath; 

      foreach (string property in propertiesToRead) 
      { 
       string propertyValue = ""; 

       if (propertiesInFile.Any(s => string.Compare(s, property, true) == 0)) 
       { 
        SwDmCustomInfoType propertyType = SwDmCustomInfoType.swDmCustomInfoText; 

        string resolvedValue; 

        propertyValue = dmDocument.GetCustomPropertyValues(property, out propertyType, out resolvedValue); 
       } 

       csvLine = csvLine + "," + FixChars(propertyValue); 
      } 

      sb.AppendLine(csvLine); 

      dmDocument.CloseDoc(); 
     } 

     static string FixChars(string s) 
     { 
      if (s.Contains(QUOTE)) s = s.Replace(QUOTE, QUOTEFORMATTED); 

      if (s.IndexOfAny(charactersToQuote) > -1) s = QUOTE + s + QUOTE; 

      return s; 
     } 

    } 
} 

Вот пример вывода enter image description here

+0

плюс один ответ –