コード例 #1
0
 public void ImportFile(Dictionary <string, int> columnMappings, byte[] importFileBytes, string encodingName, string[] separators)
 {
     if (importFileBytes.LongCount() <= ImportPolicy.MaxFileSize)
     {
         //Теперь разбираем байты
         Encoding     decoder       = Encoding.GetEncoding(encodingName);
         string       importingFile = decoder.GetString(importFileBytes);
         StringReader sr            = new StringReader(importingFile);
         string       importLine;
         while ((importLine = sr.ReadLine()) != null)
         {
             AddressModel  model   = new AddressModel();
             List <string> columns = importLine.Split(separators, StringSplitOptions.None).ToList();
             foreach (ModelMetadata propertyMetadata in AddressMetadata.Properties)
             {
                 PropertyInfo settingProperty = model.GetType().GetProperty(propertyMetadata.PropertyName);
                 //Значение которое собираемся записывать
                 string possibleValue = string.Empty;
                 if (columnMappings.ContainsKey(propertyMetadata.PropertyName) && columns.Count < columnMappings[propertyMetadata.PropertyName])
                 {
                     possibleValue = columns[columnMappings[propertyMetadata.PropertyName]];
                 }
                 if (string.IsNullOrEmpty(possibleValue))
                 {
                     object realValue = null;
                     //Метод парсинга для данного типа
                     if (propertyMetadata.ContainerType != typeof(string))
                     {
                         MethodInfo mi = propertyMetadata.ContainerType.GetMethod("Parse", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(string) }, null);
                         if (mi != null)
                         {
                             try
                             {
                                 realValue = mi.Invoke(null, new[] { possibleValue });
                             }
                             catch { /*TODO: Кривой формат строки, едем дальше, пока*/ }
                         }
                     }
                     else
                     {
                         realValue = possibleValue;
                     }
                     //Если значение не null, то надо выставлять
                     if (realValue != null)
                     {
                         settingProperty.SetValue(model, realValue, null);
                     }
                 }
             }
             SaveAddress(model);
         }
     }
     else
     {
         throw new OverflowException("Размер импортируемого файл слишком велик");
     }
 }