├── logo ├── Comma.ai ├── Comma-Small.jpg ├── Comma-Small.png ├── CSV Helper logo.ai ├── CSV Helper logo.png ├── CSV-Helper-logo-Web.jpg └── CSV-Helper-logo-Web.png ├── src ├── .nuget │ ├── NuGet.exe │ ├── NuGet.Config │ └── NuGet.targets ├── CsvHelper │ ├── CsvHelper.snk │ ├── Configuration │ │ ├── ICsvSerializerConfiguration.cs │ │ ├── MemberTypes.cs │ │ ├── DefaultCsvClassMap`1.cs │ │ ├── CsvConfigurationException.cs │ │ ├── CsvPropertyReferenceMapData.cs │ │ ├── CsvPropertyReferenceMap.cs │ │ ├── AutoMapOptions.cs │ │ └── CsvPropertyNameCollection.cs │ ├── StringHelper.cs │ ├── ICsvSerializer.cs │ ├── TypeConversion │ │ ├── GuidConverter.cs │ │ ├── CharConverter.cs │ │ ├── StringConverter.cs │ │ ├── Int32Converter.cs │ │ ├── Int64Converter.cs │ │ ├── DoubleConverter.cs │ │ ├── Int16Converter.cs │ │ ├── SByteConverter.cs │ │ ├── UInt32Converter.cs │ │ ├── DecimalConverter.cs │ │ ├── UInt16Converter.cs │ │ ├── UInt64Converter.cs │ │ ├── ByteConverter.cs │ │ ├── SingleConverter.cs │ │ ├── ITypeConverter.cs │ │ ├── CsvTypeConverterException.cs │ │ ├── IDictionaryGenericConverter.cs │ │ ├── DateTimeConverter.cs │ │ ├── DateTimeOffsetConverter.cs │ │ ├── TimeSpanConverter.cs │ │ ├── EnumConverter.cs │ │ ├── IEnumerableGenericConverter.cs │ │ ├── CollectionGenericConverter.cs │ │ ├── DefaultTypeConverter.cs │ │ ├── BooleanConverter.cs │ │ ├── IDictionaryConverter.cs │ │ ├── ArrayConverter.cs │ │ ├── EnumerableConverter.cs │ │ └── IEnumerableConverter.cs │ ├── ExceptionHelper.cs │ ├── CsvBadDataException.cs │ ├── CsvParserException.cs │ ├── CsvReaderException.cs │ ├── CsvWriterException.cs │ ├── ReflectionExtensions.cs │ ├── CsvMissingFieldException.cs │ ├── ICsvParser.cs │ ├── RecordBuilder.cs │ ├── CsvHelperException.cs │ ├── CsvHelper.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── ICsvFactory.cs │ └── ICsvWriter.cs ├── CsvHelper.Tests │ ├── CsvHelper.snk │ ├── Reading │ │ ├── EmptyTextReaderTests.cs │ │ ├── ConstantTests.cs │ │ ├── MultipleGetRecordsTests.cs │ │ ├── ShouldSkipRecordTests.cs │ │ └── MultipleHeadersTests.cs │ ├── Configuration │ │ └── CsvClassMapCollectionTests.cs │ ├── CsvWriterConstructorTests.cs │ ├── CsvParserConstructorTests.cs │ ├── Parsing │ │ └── DelimiterTests.cs │ ├── Reflection │ │ ├── CreateInstanceTests.cs │ │ └── GetMemberExpressionStackTests.cs │ ├── Mocks │ │ ├── SerializerMock.cs │ │ └── ParserMock.cs │ ├── CsvHelper.Tests.csproj │ ├── MappingInheritedClassTests.cs │ ├── Mappings │ │ ├── ReferenceConstructorArgsTests.cs │ │ ├── MapConstructorTests.cs │ │ ├── IgnoreHeaderWhiteSpaceTests.cs │ │ └── SubPropertyMappingTests.cs │ ├── CsvWriterSubClassingTests.cs │ ├── CsvReaderSubClassingTests.cs │ ├── TypeConversion │ │ ├── EnumerableConverterTests.cs │ │ ├── TypeConverterTests.cs │ │ ├── ByteConverterTests.cs │ │ ├── CharConverterTests.cs │ │ ├── TimeSpanConverterTests.cs │ │ ├── EnumConverterTests.cs │ │ └── TypeConverterOptionsTests.cs │ ├── Exceptions │ │ └── ExceptionTests.cs │ ├── Writing │ │ ├── ConstantTests.cs │ │ └── DynamicTests.cs │ ├── CsvClassMappingAutoMapTests.cs │ ├── RecordBuilderTests.cs │ ├── ReferenceMappingIndexTests.cs │ ├── DynamicProxyTests.cs │ ├── CsvReaderDefaultValueTests.cs │ ├── ParserBadDataTests.cs │ ├── MapPropertyMultipleTimesTests.cs │ ├── CsvReaderReferenceMappingPrefixTests.cs │ ├── CsvWriterReferenceMappingPrefixTests.cs │ ├── Defaults │ │ └── WritingDefaultsTests.cs │ ├── ClassMapOrderingTests.cs │ ├── LocalCultureTests.cs │ ├── CsvReaderReferenceMappingTests.cs │ └── CsvReaderConstructorTests.cs └── nuget.config ├── docs ├── Media │ ├── RawFieldsByIndexOutput.png │ ├── ReadFieldsByIndexOutput.png │ ├── CustomRecordReadingOutput.png │ ├── DefaultRecordReadingOutput.png │ └── RawFieldsByFieldNameOutput.png ├── ReadingRecords.aml ├── Content │ ├── Writing │ │ ├── WritingFields.aml │ │ ├── WritingRawFields.aml │ │ ├── WritingRecords.aml │ │ └── CreatingTheWriter.aml │ ├── Download.aml │ ├── Welcome.aml │ ├── Reading │ │ └── ReadingFields.aml │ └── CustomTypeConverter.aml └── ContentLayout.content ├── lib ├── Silverlight4ToolkitTesting │ ├── Microsoft.Silverlight.Testing.dll │ ├── Microsoft.Silverlight.Testing.pdb │ ├── Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.dll │ ├── Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.pdb │ ├── Microsoft.Silverlight.Testing.extmap.xml │ └── Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.extmap.xml ├── Silverlight5ToolkitTesting │ ├── Microsoft.Silverlight.Testing.dll │ ├── Microsoft.Silverlight.Testing.pdb │ ├── Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.dll │ ├── Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.pdb │ ├── Microsoft.Silverlight.Testing.extmap.xml │ └── Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.extmap.xml └── repositories.config ├── .gitignore ├── Push NuGet Packages.bat ├── Pack NuGet Packages.bat └── README.markdown /logo/Comma.ai: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/logo/Comma.ai -------------------------------------------------------------------------------- /logo/Comma-Small.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/logo/Comma-Small.jpg -------------------------------------------------------------------------------- /logo/Comma-Small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/logo/Comma-Small.png -------------------------------------------------------------------------------- /src/.nuget/NuGet.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/src/.nuget/NuGet.exe -------------------------------------------------------------------------------- /logo/CSV Helper logo.ai: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/logo/CSV Helper logo.ai -------------------------------------------------------------------------------- /logo/CSV Helper logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/logo/CSV Helper logo.png -------------------------------------------------------------------------------- /logo/CSV-Helper-logo-Web.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/logo/CSV-Helper-logo-Web.jpg -------------------------------------------------------------------------------- /logo/CSV-Helper-logo-Web.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/logo/CSV-Helper-logo-Web.png -------------------------------------------------------------------------------- /src/CsvHelper/CsvHelper.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/src/CsvHelper/CsvHelper.snk -------------------------------------------------------------------------------- /src/CsvHelper.Tests/CsvHelper.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/src/CsvHelper.Tests/CsvHelper.snk -------------------------------------------------------------------------------- /docs/Media/RawFieldsByIndexOutput.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/docs/Media/RawFieldsByIndexOutput.png -------------------------------------------------------------------------------- /docs/Media/ReadFieldsByIndexOutput.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/docs/Media/ReadFieldsByIndexOutput.png -------------------------------------------------------------------------------- /docs/Media/CustomRecordReadingOutput.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/docs/Media/CustomRecordReadingOutput.png -------------------------------------------------------------------------------- /docs/Media/DefaultRecordReadingOutput.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/docs/Media/DefaultRecordReadingOutput.png -------------------------------------------------------------------------------- /docs/Media/RawFieldsByFieldNameOutput.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/docs/Media/RawFieldsByFieldNameOutput.png -------------------------------------------------------------------------------- /src/nuget.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ..\lib 5 | 6 | 7 | -------------------------------------------------------------------------------- /lib/Silverlight4ToolkitTesting/Microsoft.Silverlight.Testing.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/lib/Silverlight4ToolkitTesting/Microsoft.Silverlight.Testing.dll -------------------------------------------------------------------------------- /lib/Silverlight4ToolkitTesting/Microsoft.Silverlight.Testing.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/lib/Silverlight4ToolkitTesting/Microsoft.Silverlight.Testing.pdb -------------------------------------------------------------------------------- /lib/Silverlight5ToolkitTesting/Microsoft.Silverlight.Testing.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/lib/Silverlight5ToolkitTesting/Microsoft.Silverlight.Testing.dll -------------------------------------------------------------------------------- /lib/Silverlight5ToolkitTesting/Microsoft.Silverlight.Testing.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/lib/Silverlight5ToolkitTesting/Microsoft.Silverlight.Testing.pdb -------------------------------------------------------------------------------- /src/.nuget/NuGet.Config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /lib/Silverlight4ToolkitTesting/Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/lib/Silverlight4ToolkitTesting/Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.dll -------------------------------------------------------------------------------- /lib/Silverlight4ToolkitTesting/Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/lib/Silverlight4ToolkitTesting/Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.pdb -------------------------------------------------------------------------------- /lib/Silverlight5ToolkitTesting/Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/lib/Silverlight5ToolkitTesting/Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.dll -------------------------------------------------------------------------------- /lib/Silverlight5ToolkitTesting/Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simon-thorpe/CsvHelper/master/lib/Silverlight5ToolkitTesting/Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.pdb -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *_ReSharper* 2 | *.user 3 | *.suo 4 | *.dbmdl 5 | *.schemaview 6 | *.DotSettings* 7 | *[Bb]in/ 8 | *[Oo]bj/ 9 | *[Dd]ebug/ 10 | *TestResults/ 11 | packages/ 12 | *[Ll]og.txt 13 | docs/Help 14 | NuGet/ 15 | *crunch* 16 | *project.lock.json 17 | .vs/ 18 | -------------------------------------------------------------------------------- /lib/repositories.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Push NuGet Packages.bat: -------------------------------------------------------------------------------- 1 | :: .\src\.nuget\NuGet.exe push .\NuGet\CsvHelper.*.nupkg -Source https://www.nuget.org/api/v2/package 2 | 3 | @echo off 4 | 5 | if [%1]==[] goto USAGE 6 | 7 | .\src\.nuget\NuGet.exe push %1 -source nuget.org 8 | 9 | goto DONE 10 | 11 | :USAGE 12 | 13 | cmd 14 | ::@echo Usage: %0 ^ 15 | ::pause 16 | 17 | :DONE 18 | -------------------------------------------------------------------------------- /Pack NuGet Packages.bat: -------------------------------------------------------------------------------- 1 | rmdir /S /Q NuGet 2 | 3 | @rem This currently doesn't work with net20 and net35. 4 | @rem dotnet pack src\CsvHelper --configuration release --output NuGet 5 | 6 | set msbuild="C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\msbuild" 7 | %msbuild% src\CsvHelper\ /t:Pack /p:Configuration=Release;PackageOutputPath=..\..\NuGet 8 | 9 | pause 10 | -------------------------------------------------------------------------------- /docs/ReadingRecords.aml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Coming soon... 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/CsvHelper/Configuration/ICsvSerializerConfiguration.cs: -------------------------------------------------------------------------------- 1 | namespace CsvHelper.Configuration 2 | { 3 | /// 4 | /// Configuration used for the . 5 | /// 6 | public interface ICsvSerializerConfiguration 7 | { 8 | /// 9 | /// Gets or sets the delimiter used to separate fields. 10 | /// Default is ','; 11 | /// 12 | string Delimiter { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /docs/Content/Writing/WritingFields.aml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Coming soon. 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /docs/Content/Writing/WritingRawFields.aml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Coming soon... 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /docs/Content/Writing/WritingRecords.aml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Coming soon... 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /docs/Content/Writing/CreatingTheWriter.aml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Coming soon... 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /lib/Silverlight4ToolkitTesting/Microsoft.Silverlight.Testing.extmap.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | Microsoft.Silverlight.Testing 6 | 2.0.5.0 7 | 31bf3856ad364e35 8 | Microsoft.Silverlight.Testing.dll 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /lib/Silverlight5ToolkitTesting/Microsoft.Silverlight.Testing.extmap.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | Microsoft.Silverlight.Testing 6 | 5.0.5.0 7 | 31bf3856ad364e35 8 | Microsoft.Silverlight.Testing.dll 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Reading/EmptyTextReaderTests.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | 4 | namespace CsvHelper.Tests.Reading 5 | { 6 | [TestClass] 7 | public class EmptyTextReaderTests 8 | { 9 | [TestMethod] 10 | public void EmptyStreamDoesntFailTest() 11 | { 12 | using( var stream = new MemoryStream() ) 13 | using( var reader = new StreamReader( stream ) ) 14 | using( var csv = new CsvReader( reader ) ) 15 | { 16 | Assert.IsFalse( csv.Read() ); 17 | } 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /lib/Silverlight4ToolkitTesting/Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.extmap.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight 6 | 2.0.5.0 7 | 31bf3856ad364e35 8 | Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.dll 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /lib/Silverlight5ToolkitTesting/Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.extmap.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight 6 | 5.0.5.0 7 | 31bf3856ad364e35 8 | Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.dll 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/CsvHelper/Configuration/MemberTypes.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CsvHelper.Configuration 4 | { 5 | /// 6 | /// Flags for the type of members that 7 | /// can be used for auto mapping. 8 | /// 9 | [Flags] 10 | public enum MemberTypes 11 | { 12 | /// 13 | /// No members. This is not a valid value 14 | /// and will cause an exception if used. 15 | /// 16 | None = 0, 17 | 18 | /// 19 | /// Properties on a class. 20 | /// 21 | Properties = 1, 22 | 23 | /// 24 | /// Fields on a class. 25 | /// 26 | Fields = 2 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/CsvHelper/Configuration/DefaultCsvClassMap`1.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | namespace CsvHelper.Configuration 6 | { 7 | /// 8 | /// A default that can be used 9 | /// to create a class map dynamically. 10 | /// 11 | /// 12 | public class DefaultCsvClassMap : CsvClassMap 13 | { 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Configuration/CsvClassMapCollectionTests.cs: -------------------------------------------------------------------------------- 1 | using CsvHelper.Configuration; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | 4 | namespace CsvHelper.Tests.Configuration 5 | { 6 | [TestClass] 7 | public class CsvClassMapCollectionTests 8 | { 9 | [TestMethod] 10 | public void GetChildMapWhenParentIsMappedBeforeIt() 11 | { 12 | var parentMap = new ParentMap(); 13 | var childMap = new ChildMap(); 14 | var c = new CsvClassMapCollection(); 15 | c.Add( parentMap ); 16 | c.Add( childMap ); 17 | 18 | var map = c[typeof( Child )]; 19 | Assert.AreEqual( childMap, map ); 20 | } 21 | 22 | private class Parent { } 23 | 24 | private class Child : Parent { } 25 | 26 | private sealed class ParentMap : CsvClassMap { } 27 | 28 | private sealed class ChildMap : CsvClassMap { } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/CsvWriterConstructorTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.IO; 7 | using CsvHelper.Configuration; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | namespace CsvHelper.Tests 11 | { 12 | [TestClass] 13 | public class CsvWriterConstructorTests 14 | { 15 | [TestMethod] 16 | public void EnsureInternalsAreSetupWhenPasingWriterAndConfigTest() 17 | { 18 | using( var stream = new MemoryStream() ) 19 | using( var writer = new StreamWriter( stream ) ) 20 | { 21 | var config = new CsvConfiguration(); 22 | using( var csv = new CsvWriter( writer, config ) ) 23 | { 24 | Assert.AreSame( config, csv.Configuration ); 25 | } 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/CsvParserConstructorTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.IO; 7 | using CsvHelper.Configuration; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | namespace CsvHelper.Tests 11 | { 12 | [TestClass] 13 | public class CsvParserConstructorTests 14 | { 15 | [TestMethod] 16 | public void EnsureInternalsAreSetupWhenPassingReaderAndConfigTest() 17 | { 18 | using( var stream = new MemoryStream() ) 19 | using( var reader = new StreamReader( stream ) ) 20 | { 21 | var config = new CsvConfiguration(); 22 | using( var parser = new CsvParser( reader, config ) ) 23 | { 24 | Assert.AreSame( config, parser.Configuration ); 25 | } 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Parsing/DelimiterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using Microsoft.VisualStudio.TestTools.UnitTesting; 7 | 8 | namespace CsvHelper.Tests.Parsing 9 | { 10 | [TestClass] 11 | public class DelimiterTests 12 | { 13 | [TestMethod] 14 | public void MultipleCharDelimiterWithPartOfDelimiterInFieldTest() 15 | { 16 | using( var stream = new MemoryStream() ) 17 | using( var reader = new StreamReader( stream ) ) 18 | using( var writer = new StreamWriter( stream ) ) 19 | using( var parser = new CsvParser( reader ) ) 20 | { 21 | writer.Write( "1&|$2&3&|$4\r\n" ); 22 | writer.Flush(); 23 | stream.Position = 0; 24 | 25 | parser.Configuration.Delimiter = "&|$"; 26 | var line = parser.Read(); 27 | 28 | Assert.AreEqual( 3, line.Length ); 29 | Assert.AreEqual( "1", line[0] ); 30 | Assert.AreEqual( "2&3", line[1] ); 31 | Assert.AreEqual( "4", line[2] ); 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Reflection/CreateInstanceTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using Microsoft.VisualStudio.TestTools.UnitTesting; 6 | 7 | namespace CsvHelper.Tests.Reflection 8 | { 9 | [TestClass] 10 | public class ReflectionHelperTests 11 | { 12 | [TestMethod] 13 | public void CreateInstanceTests() 14 | { 15 | var test = ReflectionHelper.CreateInstance(); 16 | 17 | Assert.IsNotNull( test ); 18 | Assert.AreEqual( "name", test.Name ); 19 | 20 | test = (Test)ReflectionHelper.CreateInstance( typeof( Test ) ); 21 | Assert.IsNotNull( test ); 22 | Assert.AreEqual( "name", test.Name ); 23 | } 24 | 25 | private class Test 26 | { 27 | public string Name 28 | { 29 | get { return "name"; } 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/CsvHelper/StringHelper.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | namespace CsvHelper 6 | { 7 | /// 8 | /// Common string tasks. 9 | /// 10 | internal static class StringHelper 11 | { 12 | /// 13 | /// Tests if a string is null or whitespace. 14 | /// 15 | /// The string to test. 16 | /// True if the string is null or whitespace, otherwise false. 17 | public static bool IsNullOrWhiteSpace( string s ) 18 | { 19 | if( s == null ) 20 | { 21 | return true; 22 | } 23 | 24 | for( var i = 0; i < s.Length; i++ ) 25 | { 26 | if( !char.IsWhiteSpace( s[i] ) ) 27 | { 28 | return false; 29 | } 30 | } 31 | 32 | return true; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CsvHelper/ICsvSerializer.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.IO; 7 | using CsvHelper.Configuration; 8 | 9 | namespace CsvHelper 10 | { 11 | /// 12 | /// Defines methods used to serialize data into a CSV file. 13 | /// 14 | public interface ICsvSerializer : IDisposable 15 | { 16 | /// 17 | /// Gets the . 18 | /// 19 | TextWriter TextWriter { get; } 20 | 21 | /// 22 | /// Gets the configuration. 23 | /// 24 | ICsvSerializerConfiguration Configuration { get; } 25 | 26 | /// 27 | /// Writes a record to the CSV file. 28 | /// 29 | /// The record to write. 30 | void Write( string[] record ); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /docs/Content/Download.aml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | Downloads 11 | 12 | 13 | 14 | 15 | Releases and Documentation 16 | http://github.com/JoshClose/CsvHelper/downloads 17 | _blank 18 | 19 | 20 | 21 | 22 | 23 | Source 24 | http://github.com/JoshClose/CsvHelper 25 | _blank 26 | 27 | 28 | 29 | 30 |
31 | 32 | 33 | 34 |
35 |
-------------------------------------------------------------------------------- /src/CsvHelper.Tests/Mocks/SerializerMock.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using CsvHelper.Configuration; 7 | 8 | namespace CsvHelper.Tests.Mocks 9 | { 10 | public class SerializerMock : ICsvSerializer 11 | { 12 | private readonly List records = new List(); 13 | private readonly bool throwExceptionOnWrite; 14 | 15 | public TextWriter TextWriter { get; } 16 | 17 | public ICsvSerializerConfiguration Configuration { get; private set; } 18 | 19 | public List Records 20 | { 21 | get { return records; } 22 | } 23 | 24 | public SerializerMock( bool throwExceptionOnWrite = false ) 25 | { 26 | Configuration = new CsvConfiguration(); 27 | this.throwExceptionOnWrite = throwExceptionOnWrite; 28 | } 29 | 30 | public void Write( string[] record ) 31 | { 32 | if( throwExceptionOnWrite ) 33 | { 34 | throw new Exception( "Mock Write exception." ); 35 | } 36 | 37 | records.Add( record ); 38 | } 39 | 40 | public void Dispose() 41 | { 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/CsvHelper.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | netcoreapp1.1 6 | True 7 | CsvHelper.snk 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | $(DefineConstants);NETCORE 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/MappingInheritedClassTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | using CsvHelper.Configuration; 10 | using Microsoft.VisualStudio.TestTools.UnitTesting; 11 | 12 | namespace CsvHelper.Tests 13 | { 14 | [TestClass] 15 | public class MappingInheritedClassTests 16 | { 17 | [TestMethod] 18 | public void Test() 19 | { 20 | var map = new AMap(); 21 | Assert.AreEqual( 2, map.PropertyMaps.Count ); 22 | } 23 | 24 | private interface IA 25 | { 26 | int Id { get; set; } 27 | } 28 | 29 | private class A : IA 30 | { 31 | public int Id { get; set; } 32 | 33 | public int Name { get; set; } 34 | } 35 | 36 | private sealed class AMap : CsvClassMap where T : IA 37 | { 38 | public AMap() 39 | { 40 | AutoMap(); 41 | Map( m => m.Id ); 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Mappings/ReferenceConstructorArgsTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using CsvHelper.Configuration; 6 | using Microsoft.VisualStudio.TestTools.UnitTesting; 7 | 8 | namespace CsvHelper.Tests.Mappings 9 | { 10 | [TestClass] 11 | public class ReferenceConstructorArgsTests 12 | { 13 | [TestMethod] 14 | public void Test() 15 | { 16 | var map = new AMap( "A Field" ); 17 | var name = map.ReferenceMaps[0].Data.Mapping.PropertyMaps.Find( m => m.Name ).Data.Names[0]; 18 | Assert.AreEqual( "B Field", name ); 19 | } 20 | 21 | private class A 22 | { 23 | public string Name { get; set; } 24 | 25 | public B B { get; set; } 26 | } 27 | 28 | private class B 29 | { 30 | public string Name { get; set; } 31 | } 32 | 33 | private sealed class AMap : CsvClassMap 34 | { 35 | public AMap( string name ) 36 | { 37 | Map( m => m.Name ).Name( name ); 38 | References( m => m.B, "B Field" ); 39 | } 40 | } 41 | 42 | private sealed class BMap : CsvClassMap 43 | { 44 | public BMap( string name ) 45 | { 46 | Map( m => m.Name ).Name( name ); 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Mappings/MapConstructorTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using CsvHelper.Configuration; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | namespace CsvHelper.Tests.Mappings 11 | { 12 | [TestClass] 13 | public class MapConstructorTests 14 | { 15 | [TestMethod] 16 | public void NoConstructor() 17 | { 18 | using( var stream = new MemoryStream() ) 19 | using( var reader = new StreamReader( stream ) ) 20 | using( var csv = new CsvReader( reader ) ) 21 | { 22 | try 23 | { 24 | csv.Configuration.RegisterClassMap(); 25 | Assert.Fail(); 26 | } 27 | catch( InvalidOperationException ex ) 28 | { 29 | Assert.AreEqual( "No public parameterless constructor found.", ex.Message ); 30 | } 31 | } 32 | } 33 | 34 | private class Test 35 | { 36 | public int Id { get; set; } 37 | public string Name { get; set; } 38 | } 39 | 40 | private sealed class TestMap : CsvClassMap 41 | { 42 | private TestMap() 43 | { 44 | Map( m => m.Id ); 45 | Map( m => m.Name ); 46 | } 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/CsvWriterSubClassingTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using CsvHelper.Configuration; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | namespace CsvHelper.Tests 11 | { 12 | [TestClass] 13 | public class CsvWriterSubClassingTests 14 | { 15 | [TestMethod] 16 | public void WriteRecordTest() 17 | { 18 | var data = new List 19 | { 20 | new Test { Id = 1, Name = "one" }, 21 | new Test { Id = 2, Name = "two" } 22 | }; 23 | 24 | var stream = new MemoryStream(); 25 | var writer = new StreamWriter( stream ); 26 | var csvWriter = new MyCsvWriter( writer ); 27 | 28 | csvWriter.WriteRecords( data ); 29 | } 30 | 31 | private class MyCsvWriter : CsvWriter 32 | { 33 | public MyCsvWriter( TextWriter writer ) : base( writer ){} 34 | } 35 | 36 | private class Test 37 | { 38 | public int Id { get; set; } 39 | public string Name { get; set; } 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/CsvReaderSubClassingTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using CsvHelper.Configuration; 8 | using CsvHelper.Tests.Mocks; 9 | using Microsoft.VisualStudio.TestTools.UnitTesting; 10 | 11 | namespace CsvHelper.Tests 12 | { 13 | [TestClass] 14 | public class CsvReaderSubClassingTests 15 | { 16 | [TestMethod] 17 | public void GetRecordTest() 18 | { 19 | var data = new List 20 | { 21 | new[] { "Id", "Name" }, 22 | new[] { "1", "one" }, 23 | new[] { "2", "two" }, 24 | null 25 | }; 26 | 27 | var parserMock = new ParserMock( new Queue( data ) ); 28 | 29 | var csvReader = new MyCsvReader( parserMock ); 30 | csvReader.GetRecords().ToList(); 31 | } 32 | 33 | private class MyCsvReader : CsvReader 34 | { 35 | public MyCsvReader( ICsvParser parser ) : base( parser ){} 36 | } 37 | 38 | private class Test 39 | { 40 | public int Id { get; set; } 41 | public string Name { get; set; } 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/GuidConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Globalization; 7 | using CsvHelper.Configuration; 8 | 9 | namespace CsvHelper.TypeConversion 10 | { 11 | /// 12 | /// Converts a to and from a . 13 | /// 14 | public class GuidConverter : DefaultTypeConverter 15 | { 16 | /// 17 | /// Converts the string to an object. 18 | /// 19 | /// The string to convert to an object. 20 | /// The for the current record. 21 | /// The for the property/field being created. 22 | /// The object created from the string. 23 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 24 | { 25 | if( text == null ) 26 | { 27 | return base.ConvertFromString( text, row, propertyMapData ); 28 | } 29 | 30 | return new Guid( text ); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Mappings/IgnoreHeaderWhiteSpaceTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using CsvHelper.Configuration; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | namespace CsvHelper.Tests.Mappings 11 | { 12 | [TestClass] 13 | public class IgnoreHeaderWhiteSpaceTests 14 | { 15 | [TestMethod] 16 | public void Blah() 17 | { 18 | using( var stream = new MemoryStream() ) 19 | using( var reader = new StreamReader( stream ) ) 20 | using( var writer = new StreamWriter( stream ) ) 21 | using( var csv = new CsvReader( reader ) ) 22 | { 23 | writer.WriteLine( "The Id,The Name" ); 24 | writer.WriteLine( "1,one" ); 25 | writer.Flush(); 26 | stream.Position = 0; 27 | 28 | csv.Configuration.RegisterClassMap(); 29 | var records = csv.GetRecords().ToList(); 30 | 31 | Assert.AreEqual( 1, records[0].Id ); 32 | Assert.AreEqual( "one", records[0].Name ); 33 | } 34 | } 35 | 36 | private class Test 37 | { 38 | public int Id { get; set; } 39 | public string Name { get; set; } 40 | } 41 | 42 | private sealed class TestMap : CsvClassMap 43 | { 44 | public TestMap() 45 | { 46 | Map( m => m.Id ).Name( "The Id" ); 47 | Map( m => m.Name ).Name( "The Name" ); 48 | } 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/TypeConversion/EnumerableConverterTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.Collections.Generic; 6 | using System.Globalization; 7 | using System.Text; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | using System.IO; 10 | using CsvHelper.Configuration; 11 | using CsvHelper.Tests.Mocks; 12 | using CsvHelper.TypeConversion; 13 | 14 | namespace CsvHelper.Tests.TypeConversion 15 | { 16 | [TestClass] 17 | public class EnumerableConverterTests 18 | { 19 | [TestMethod] 20 | public void ConvertTest() 21 | { 22 | var converter = new EnumerableConverter(); 23 | 24 | var propertyMapData = new CsvPropertyMapData( null ); 25 | propertyMapData.TypeConverterOptions.CultureInfo = CultureInfo.CurrentCulture; 26 | 27 | try 28 | { 29 | converter.ConvertFromString( "", null, propertyMapData ); 30 | Assert.Fail(); 31 | } 32 | catch( CsvTypeConverterException ) 33 | { 34 | } 35 | try 36 | { 37 | converter.ConvertToString( 5, null, propertyMapData ); 38 | Assert.Fail(); 39 | } 40 | catch( CsvTypeConverterException ) 41 | { 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Reading/ConstantTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using CsvHelper.Configuration; 7 | using CsvHelper.Tests.Mocks; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | namespace CsvHelper.Tests.Reading 11 | { 12 | [TestClass] 13 | public class ConstantTests 14 | { 15 | [TestMethod] 16 | public void ConstantAlwaysReturnsSameValueTest() 17 | { 18 | var rows = new Queue(); 19 | rows.Enqueue( new[] { "Id", "Name" } ); 20 | rows.Enqueue( new[] { "1", "one" } ); 21 | rows.Enqueue( new[] { "2", "two" } ); 22 | rows.Enqueue( null ); 23 | var parser = new ParserMock( rows ); 24 | 25 | var csv = new CsvReader( parser ); 26 | csv.Configuration.RegisterClassMap(); 27 | var records = csv.GetRecords().ToList(); 28 | 29 | Assert.AreEqual( 1, records[0].Id ); 30 | Assert.AreEqual( "constant", records[0].Name ); 31 | Assert.AreEqual( 2, records[1].Id ); 32 | Assert.AreEqual( "constant", records[0].Name ); 33 | } 34 | 35 | private class Test 36 | { 37 | public int Id { get; set; } 38 | public string Name { get; set; } 39 | } 40 | 41 | private sealed class TestMap : CsvClassMap 42 | { 43 | public TestMap() 44 | { 45 | Map( m => m.Id ); 46 | Map( m => m.Name ).Constant( "constant" ); 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Reading/MultipleGetRecordsTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | 9 | namespace CsvHelper.Tests.Reading 10 | { 11 | [TestClass] 12 | public class MultipleGetRecordsTests 13 | { 14 | [TestMethod] 15 | public void Blah() 16 | { 17 | using( var stream = new MemoryStream() ) 18 | using( var reader = new StreamReader( stream ) ) 19 | using( var writer = new StreamWriter( stream ) ) 20 | using( var csv = new CsvReader( reader ) ) 21 | { 22 | writer.WriteLine( "Id,Name" ); 23 | writer.WriteLine( "1,one" ); 24 | writer.Flush(); 25 | stream.Position = 0; 26 | 27 | var records = csv.GetRecords().ToList(); 28 | 29 | var position = stream.Position; 30 | writer.WriteLine( "2,two" ); 31 | writer.Flush(); 32 | stream.Position = position; 33 | 34 | records = csv.GetRecords().ToList(); 35 | 36 | writer.WriteLine( "2,two" ); 37 | writer.Flush(); 38 | stream.Position = position; 39 | 40 | Assert.AreEqual( 1, records.Count ); 41 | Assert.AreEqual( 2, records[0].Id ); 42 | Assert.AreEqual( "two", records[0].Name ); 43 | } 44 | } 45 | 46 | private class Test 47 | { 48 | public int Id { get; set; } 49 | public string Name { get; set; } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/CharConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.Globalization; 6 | using CsvHelper.Configuration; 7 | 8 | namespace CsvHelper.TypeConversion 9 | { 10 | /// 11 | /// Converts a to and from a . 12 | /// 13 | public class CharConverter : DefaultTypeConverter 14 | { 15 | /// 16 | /// Converts the string to an object. 17 | /// 18 | /// The string to convert to an object. 19 | /// The for the current record. 20 | /// The for the property/field being created. 21 | /// The object created from the string. 22 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 23 | { 24 | if( text != null && text.Length > 1 ) 25 | { 26 | text = text.Trim(); 27 | } 28 | 29 | char c; 30 | if( char.TryParse( text, out c ) ) 31 | { 32 | return c; 33 | } 34 | 35 | return base.ConvertFromString( text, row, propertyMapData ); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Reflection/GetMemberExpressionStackTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Microsoft.VisualStudio.TestTools.UnitTesting; 7 | 8 | namespace CsvHelper.Tests.Reflection 9 | { 10 | [TestClass] 11 | public class GetPropertiesTests 12 | { 13 | [TestMethod] 14 | public void FirstLevelTest() 15 | { 16 | var stack = ReflectionHelper.GetMembers( a => a.P1 ); 17 | 18 | Assert.AreEqual( 1, stack.Count ); 19 | Assert.AreEqual( "P1", stack.Pop().Name ); 20 | } 21 | 22 | [TestMethod] 23 | public void LastLevelTest() 24 | { 25 | var stack = ReflectionHelper.GetMembers( a => a.B.C.D.P4 ); 26 | 27 | Assert.AreEqual( 4, stack.Count ); 28 | Assert.AreEqual( "B", stack.Pop().Name ); 29 | Assert.AreEqual( "C", stack.Pop().Name ); 30 | Assert.AreEqual( "D", stack.Pop().Name ); 31 | Assert.AreEqual( "P4", stack.Pop().Name ); 32 | } 33 | 34 | public void ThirdLevelTest() 35 | { 36 | } 37 | 38 | private class A 39 | { 40 | public string P1 { get; set; } 41 | public B B { get; set; } 42 | } 43 | 44 | private class B 45 | { 46 | public string P2 { get; set; } 47 | public C C { get; set; } 48 | } 49 | 50 | private class C 51 | { 52 | public string P3 { get; set; } 53 | public D D { get; set; } 54 | } 55 | 56 | private class D 57 | { 58 | public string P4 { get; set; } 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/StringConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.Globalization; 6 | using CsvHelper.Configuration; 7 | 8 | namespace CsvHelper.TypeConversion 9 | { 10 | /// 11 | /// Converts a to and from a . 12 | /// 13 | public class StringConverter : DefaultTypeConverter 14 | { 15 | /// 16 | /// Converts the string to an object. 17 | /// 18 | /// The string to convert to an object. 19 | /// The for the current record. 20 | /// The for the property/field being created. 21 | /// The object created from the string. 22 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 23 | { 24 | if( text == null ) 25 | { 26 | return string.Empty; 27 | } 28 | 29 | foreach( var nullValue in propertyMapData.TypeConverterOptions.NullValues ) 30 | { 31 | if( text == nullValue ) 32 | { 33 | return null; 34 | } 35 | } 36 | 37 | return text; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /docs/ContentLayout.content: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/Int32Converter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.Globalization; 6 | using CsvHelper.Configuration; 7 | 8 | namespace CsvHelper.TypeConversion 9 | { 10 | /// 11 | /// Converts an to and from a . 12 | /// 13 | public class Int32Converter : DefaultTypeConverter 14 | { 15 | /// 16 | /// Converts the string to an object. 17 | /// 18 | /// The string to convert to an object. 19 | /// The for the current record. 20 | /// The for the property/field being created. 21 | /// The object created from the string. 22 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 23 | { 24 | var numberStyle = propertyMapData.TypeConverterOptions.NumberStyle ?? NumberStyles.Integer; 25 | 26 | int i; 27 | if( int.TryParse( text, numberStyle, propertyMapData.TypeConverterOptions.CultureInfo, out i ) ) 28 | { 29 | return i; 30 | } 31 | 32 | return base.ConvertFromString( text, row, propertyMapData ); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/Int64Converter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.Globalization; 6 | using CsvHelper.Configuration; 7 | 8 | namespace CsvHelper.TypeConversion 9 | { 10 | /// 11 | /// Converts an to and from a . 12 | /// 13 | public class Int64Converter : DefaultTypeConverter 14 | { 15 | /// 16 | /// Converts the string to an object. 17 | /// 18 | /// The string to convert to an object. 19 | /// The for the current record. 20 | /// The for the property/field being created. 21 | /// The object created from the string. 22 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 23 | { 24 | var numberStyle = propertyMapData.TypeConverterOptions.NumberStyle ?? NumberStyles.Integer; 25 | 26 | long l; 27 | if( long.TryParse( text, numberStyle, propertyMapData.TypeConverterOptions.CultureInfo, out l ) ) 28 | { 29 | return l; 30 | } 31 | 32 | return base.ConvertFromString( text, row, propertyMapData ); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/TypeConversion/TypeConverterTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | using Microsoft.VisualStudio.TestTools.UnitTesting; 10 | using CsvHelper.Configuration; 11 | using CsvHelper.Tests.Mocks; 12 | using CsvHelper.TypeConversion; 13 | 14 | namespace CsvHelper.Tests.TypeConversion 15 | { 16 | [TestClass] 17 | public class TypeConverterTests 18 | { 19 | [TestMethod] 20 | public void ReaderInheritedConverter() 21 | { 22 | var queue = new Queue(); 23 | queue.Enqueue( new[] { "1" } ); 24 | queue.Enqueue( null ); 25 | var parserMock = new ParserMock( queue ); 26 | var csv = new CsvReader( parserMock ); 27 | csv.Configuration.HasHeaderRecord = false; 28 | csv.Configuration.RegisterClassMap(); 29 | var list = csv.GetRecords().ToList(); 30 | } 31 | 32 | private class Test 33 | { 34 | public int IntColumn { get; set; } 35 | } 36 | 37 | private sealed class TestMap : CsvClassMap 38 | { 39 | public TestMap() 40 | { 41 | Map( m => m.IntColumn ).Index( 0 ).TypeConverter(); 42 | } 43 | } 44 | 45 | private class Converter : Int32Converter 46 | { 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/CsvHelper/ExceptionHelper.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Text; 8 | using System.Linq; 9 | 10 | namespace CsvHelper 11 | { 12 | /// 13 | /// Common exception tasks. 14 | /// 15 | internal static class ExceptionHelper 16 | { 17 | public static void AddExceptionData( CsvHelperException exception, int row, Type type, int? currentIndex, Dictionary> namedIndexes, string[] currentRecord ) 18 | { 19 | exception.Row = row; 20 | exception.Type = type; 21 | exception.FieldIndex = currentIndex ?? -1; 22 | 23 | if( namedIndexes != null ) 24 | { 25 | var fieldName = ( from pair in namedIndexes 26 | from index in pair.Value 27 | where index == currentIndex 28 | select pair.Key ).SingleOrDefault(); 29 | if( fieldName != null ) 30 | { 31 | exception.FieldName = fieldName; 32 | } 33 | } 34 | 35 | if( currentRecord != null && currentIndex > -1 && currentIndex < currentRecord.Length ) 36 | { 37 | if( currentIndex.Value < currentRecord.Length ) 38 | { 39 | var fieldValue = currentRecord[currentIndex.Value]; 40 | exception.FieldValue = fieldValue; 41 | } 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/DoubleConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.Globalization; 6 | using CsvHelper.Configuration; 7 | 8 | namespace CsvHelper.TypeConversion 9 | { 10 | /// 11 | /// Converts a to and from a . 12 | /// 13 | public class DoubleConverter : DefaultTypeConverter 14 | { 15 | /// 16 | /// Converts the string to an object. 17 | /// 18 | /// The string to convert to an object. 19 | /// The for the current record. 20 | /// The for the property/field being created. 21 | /// The object created from the string. 22 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 23 | { 24 | var numberStyle = propertyMapData.TypeConverterOptions.NumberStyle ?? NumberStyles.Float; 25 | 26 | double d; 27 | if( double.TryParse( text, numberStyle, propertyMapData.TypeConverterOptions.CultureInfo, out d ) ) 28 | { 29 | return d; 30 | } 31 | 32 | return base.ConvertFromString( text, row, propertyMapData ); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/Int16Converter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.Globalization; 6 | using CsvHelper.Configuration; 7 | 8 | namespace CsvHelper.TypeConversion 9 | { 10 | /// 11 | /// Converts a to and from a . 12 | /// 13 | public class Int16Converter : DefaultTypeConverter 14 | { 15 | /// 16 | /// Converts the string to an object. 17 | /// 18 | /// The string to convert to an object. 19 | /// The for the current record. 20 | /// The for the property/field being created. 21 | /// The object created from the string. 22 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 23 | { 24 | var numberStyle = propertyMapData.TypeConverterOptions.NumberStyle ?? NumberStyles.Integer; 25 | 26 | short s; 27 | if( short.TryParse( text, numberStyle, propertyMapData.TypeConverterOptions.CultureInfo, out s ) ) 28 | { 29 | return s; 30 | } 31 | 32 | return base.ConvertFromString( text, row, propertyMapData ); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/SByteConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.Globalization; 6 | using CsvHelper.Configuration; 7 | 8 | namespace CsvHelper.TypeConversion 9 | { 10 | /// 11 | /// Converts a to and from a . 12 | /// 13 | public class SByteConverter : DefaultTypeConverter 14 | { 15 | /// 16 | /// Converts the string to an object. 17 | /// 18 | /// The string to convert to an object. 19 | /// The for the current record. 20 | /// The for the property/field being created. 21 | /// The object created from the string. 22 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 23 | { 24 | var numberStyle = propertyMapData.TypeConverterOptions.NumberStyle ?? NumberStyles.Integer; 25 | 26 | sbyte sb; 27 | if( sbyte.TryParse( text, numberStyle, propertyMapData.TypeConverterOptions.CultureInfo, out sb ) ) 28 | { 29 | return sb; 30 | } 31 | 32 | return base.ConvertFromString( text, row, propertyMapData ); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/UInt32Converter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.Globalization; 6 | using CsvHelper.Configuration; 7 | 8 | namespace CsvHelper.TypeConversion 9 | { 10 | /// 11 | /// Converts a to and from a . 12 | /// 13 | public class UInt32Converter : DefaultTypeConverter 14 | { 15 | /// 16 | /// Converts the string to an object. 17 | /// 18 | /// The string to convert to an object. 19 | /// The for the current record. 20 | /// The for the property/field being created. 21 | /// The object created from the string. 22 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 23 | { 24 | var numberStyle = propertyMapData.TypeConverterOptions.NumberStyle ?? NumberStyles.Integer; 25 | 26 | uint ui; 27 | if( uint.TryParse( text, numberStyle, propertyMapData.TypeConverterOptions.CultureInfo, out ui ) ) 28 | { 29 | return ui; 30 | } 31 | 32 | return base.ConvertFromString( text, row, propertyMapData ); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/DecimalConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.Globalization; 6 | using CsvHelper.Configuration; 7 | 8 | namespace CsvHelper.TypeConversion 9 | { 10 | /// 11 | /// Converts a to and from a . 12 | /// 13 | public class DecimalConverter : DefaultTypeConverter 14 | { 15 | /// 16 | /// Converts the string to an object. 17 | /// 18 | /// The string to convert to an object. 19 | /// The for the current record. 20 | /// The for the property/field being created. 21 | /// The object created from the string. 22 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 23 | { 24 | var numberStyle = propertyMapData.TypeConverterOptions.NumberStyle ?? NumberStyles.Float; 25 | 26 | decimal d; 27 | if( decimal.TryParse( text, numberStyle, propertyMapData.TypeConverterOptions.CultureInfo, out d ) ) 28 | { 29 | return d; 30 | } 31 | 32 | return base.ConvertFromString( text, row, propertyMapData ); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/UInt16Converter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.Globalization; 6 | using CsvHelper.Configuration; 7 | 8 | namespace CsvHelper.TypeConversion 9 | { 10 | /// 11 | /// Converts a to and from a . 12 | /// 13 | public class UInt16Converter : DefaultTypeConverter 14 | { 15 | /// 16 | /// Converts the string to an object. 17 | /// 18 | /// The string to convert to an object. 19 | /// The for the current record. 20 | /// The for the property/field being created. 21 | /// The object created from the string. 22 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 23 | { 24 | var numberStyle = propertyMapData.TypeConverterOptions.NumberStyle ?? NumberStyles.Integer; 25 | 26 | ushort us; 27 | if( ushort.TryParse( text, numberStyle, propertyMapData.TypeConverterOptions.CultureInfo, out us ) ) 28 | { 29 | return us; 30 | } 31 | 32 | return base.ConvertFromString( text, row, propertyMapData ); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/UInt64Converter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.Globalization; 6 | using CsvHelper.Configuration; 7 | 8 | namespace CsvHelper.TypeConversion 9 | { 10 | /// 11 | /// Converts a to and from a . 12 | /// 13 | public class UInt64Converter : DefaultTypeConverter 14 | { 15 | /// 16 | /// Converts the string to an object. 17 | /// 18 | /// The string to convert to an object. 19 | /// The for the current record. 20 | /// The for the property/field being created. 21 | /// The object created from the string. 22 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 23 | { 24 | var numberStyle = propertyMapData.TypeConverterOptions.NumberStyle ?? NumberStyles.Integer; 25 | 26 | ulong ul; 27 | if( ulong.TryParse( text, numberStyle, propertyMapData.TypeConverterOptions.CultureInfo, out ul ) ) 28 | { 29 | return ul; 30 | } 31 | 32 | return base.ConvertFromString( text, row, propertyMapData ); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Exceptions/ExceptionTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | 6 | using System; 7 | using System.IO; 8 | using System.Linq; 9 | using System.Text; 10 | using Microsoft.VisualStudio.TestTools.UnitTesting; 11 | 12 | namespace CsvHelper.Tests.Exceptions 13 | { 14 | [TestClass] 15 | public class ExceptionTests 16 | { 17 | [TestMethod] 18 | public void NoDefaultConstructorTest() 19 | { 20 | using( var stream = new MemoryStream() ) 21 | using( var reader = new StreamReader( stream ) ) 22 | using( var writer = new StreamWriter( stream ) ) 23 | using( var csv = new CsvReader( reader ) ) 24 | { 25 | writer.WriteLine( "Id,Name" ); 26 | writer.WriteLine( "1,2" ); 27 | writer.WriteLine( "3,4" ); 28 | writer.Flush(); 29 | stream.Position = 0; 30 | 31 | try 32 | { 33 | var list = csv.GetRecords().ToList(); 34 | Assert.Fail(); 35 | } 36 | catch( CsvReaderException ) 37 | { 38 | } 39 | } 40 | } 41 | 42 | private class NoDefaultConstructor 43 | { 44 | public int Id { get; set; } 45 | 46 | public string Name { get; set; } 47 | 48 | public NoDefaultConstructor( int id, string name ) 49 | { 50 | Id = id; 51 | Name = name; 52 | } 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/ByteConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Globalization; 7 | using CsvHelper.Configuration; 8 | 9 | namespace CsvHelper.TypeConversion 10 | { 11 | /// 12 | /// Converts a to and from a . 13 | /// 14 | public class ByteConverter : DefaultTypeConverter 15 | { 16 | /// 17 | /// Converts the string to an object. 18 | /// 19 | /// The string to convert to an object. 20 | /// The for the current record. 21 | /// The for the property/field being created. 22 | /// The object created from the string. 23 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 24 | { 25 | var numberStyle = propertyMapData.TypeConverterOptions.NumberStyle ?? NumberStyles.Integer; 26 | 27 | byte b; 28 | if( byte.TryParse( text, numberStyle, propertyMapData.TypeConverterOptions.CultureInfo, out b ) ) 29 | { 30 | return b; 31 | } 32 | 33 | return base.ConvertFromString( text, row, propertyMapData ); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/SingleConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.Globalization; 6 | using CsvHelper.Configuration; 7 | using System; 8 | 9 | namespace CsvHelper.TypeConversion 10 | { 11 | /// 12 | /// Converts a to and from a . 13 | /// 14 | public class SingleConverter : DefaultTypeConverter 15 | { 16 | /// 17 | /// Converts the string to an object. 18 | /// 19 | /// The string to convert to an object. 20 | /// The for the current record. 21 | /// The for the property/field being created. 22 | /// The object created from the string. 23 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 24 | { 25 | var numberStyle = propertyMapData.TypeConverterOptions.NumberStyle ?? NumberStyles.Float; 26 | 27 | float f; 28 | if( float.TryParse( text, numberStyle, propertyMapData.TypeConverterOptions.CultureInfo, out f ) ) 29 | { 30 | return f; 31 | } 32 | 33 | return base.ConvertFromString( text, row, propertyMapData ); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Writing/ConstantTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using CsvHelper.Configuration; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | namespace CsvHelper.Tests.Writing 11 | { 12 | [TestClass] 13 | public class ConstantTests 14 | { 15 | [TestMethod] 16 | public void SameValueIsWrittenForEveryRecordTest() 17 | { 18 | using( var stream = new MemoryStream() ) 19 | using( var reader = new StreamReader( stream ) ) 20 | using( var writer = new StreamWriter( stream ) ) 21 | using( var csv = new CsvWriter( writer ) ) 22 | { 23 | var records = new List 24 | { 25 | new Test { Id = 1, Name = "one" }, 26 | new Test { Id = 2, Name = "two" } 27 | }; 28 | 29 | csv.Configuration.RegisterClassMap(); 30 | csv.WriteRecords( records ); 31 | writer.Flush(); 32 | stream.Position = 0; 33 | 34 | var expected = new StringBuilder(); 35 | expected.AppendLine( "Id,Name" ); 36 | expected.AppendLine( "1,constant" ); 37 | expected.AppendLine( "2,constant" ); 38 | 39 | var result = reader.ReadToEnd(); 40 | 41 | Assert.AreEqual( expected.ToString(), result ); 42 | } 43 | } 44 | 45 | private class Test 46 | { 47 | public int Id { get; set; } 48 | public string Name { get; set; } 49 | } 50 | 51 | private sealed class TestMap : CsvClassMap 52 | { 53 | public TestMap() 54 | { 55 | Map( m => m.Id ); 56 | Map( m => m.Name ).Constant( "constant" ); 57 | } 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/ITypeConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Globalization; 7 | using CsvHelper.Configuration; 8 | 9 | namespace CsvHelper.TypeConversion 10 | { 11 | /// 12 | /// Converts objects to and from strings. 13 | /// 14 | public interface ITypeConverter 15 | { 16 | /// 17 | /// Converts the object to a string. 18 | /// 19 | /// The object to convert to a string. 20 | /// The for the current record. 21 | /// The for the property/field being written. 22 | /// The string representation of the object. 23 | string ConvertToString( object value, ICsvWriterRow row, CsvPropertyMapData propertyMapData ); 24 | 25 | /// 26 | /// Converts the string to an object. 27 | /// 28 | /// The string to convert to an object. 29 | /// The for the current record. 30 | /// The for the property/field being created. 31 | /// The object created from the string. 32 | object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/CsvHelper/CsvBadDataException.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | 7 | namespace CsvHelper 8 | { 9 | /// 10 | /// Represents errors that occur due to bad data. 11 | /// 12 | public class CsvBadDataException : CsvHelperException 13 | { 14 | /// 15 | /// Initializes a new instance of the class. 16 | /// 17 | public CsvBadDataException() {} 18 | 19 | /// 20 | /// Initializes a new instance of the class 21 | /// with a specified error message. 22 | /// 23 | /// The message that describes the error. 24 | public CsvBadDataException( string message ) : base( message ) {} 25 | 26 | /// 27 | /// Initializes a new instance of the class 28 | /// with a specified error message and a reference to the inner exception that 29 | /// is the cause of this exception. 30 | /// 31 | /// The error message that explains the reason for the exception. 32 | /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. 33 | public CsvBadDataException( string message, Exception innerException ) : base( message, innerException ) { } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CsvHelper/CsvParserException.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | 7 | namespace CsvHelper 8 | { 9 | /// 10 | /// Represents errors that occur while parsing a CSV file. 11 | /// 12 | public class CsvParserException : CsvHelperException 13 | { 14 | /// 15 | /// Initializes a new instance of the class. 16 | /// 17 | public CsvParserException() {} 18 | 19 | /// 20 | /// Initializes a new instance of the class 21 | /// with a specified error message. 22 | /// 23 | /// The message that describes the error. 24 | public CsvParserException( string message ) : base( message ) {} 25 | 26 | /// 27 | /// Initializes a new instance of the class 28 | /// with a specified error message and a reference to the inner exception that 29 | /// is the cause of this exception. 30 | /// 31 | /// The error message that explains the reason for the exception. 32 | /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. 33 | public CsvParserException( string message, Exception innerException ) : base( message, innerException ) { } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CsvHelper/CsvReaderException.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | 7 | namespace CsvHelper 8 | { 9 | /// 10 | /// Represents errors that occur while reading a CSV file. 11 | /// 12 | public class CsvReaderException : CsvHelperException 13 | { 14 | /// 15 | /// Initializes a new instance of the class. 16 | /// 17 | public CsvReaderException() {} 18 | 19 | /// 20 | /// Initializes a new instance of the class 21 | /// with a specified error message. 22 | /// 23 | /// The message that describes the error. 24 | public CsvReaderException( string message ) : base( message ) {} 25 | 26 | /// 27 | /// Initializes a new instance of the class 28 | /// with a specified error message and a reference to the inner exception that 29 | /// is the cause of this exception. 30 | /// 31 | /// The error message that explains the reason for the exception. 32 | /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. 33 | public CsvReaderException( string message, Exception innerException ) : base( message, innerException ) { } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CsvHelper/CsvWriterException.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | 7 | namespace CsvHelper 8 | { 9 | /// 10 | /// Represents errors that occur while writing a CSV file. 11 | /// 12 | public class CsvWriterException : CsvHelperException 13 | { 14 | /// 15 | /// Initializes a new instance of the class. 16 | /// 17 | public CsvWriterException() {} 18 | 19 | /// 20 | /// Initializes a new instance of the class 21 | /// with a specified error message. 22 | /// 23 | /// The message that describes the error. 24 | public CsvWriterException( string message ) : base( message ) {} 25 | 26 | /// 27 | /// Initializes a new instance of the class 28 | /// with a specified error message and a reference to the inner exception that 29 | /// is the cause of this exception. 30 | /// 31 | /// The error message that explains the reason for the exception. 32 | /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. 33 | public CsvWriterException( string message, Exception innerException ) : base( message, innerException ) { } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/CsvClassMappingAutoMapTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | using Microsoft.VisualStudio.TestTools.UnitTesting; 10 | using CsvHelper.Configuration; 11 | 12 | namespace CsvHelper.Tests 13 | { 14 | [TestClass] 15 | public class CsvClassMappingAutoMapTests 16 | { 17 | [TestMethod] 18 | public void Test() 19 | { 20 | var aMap = new AMap(); 21 | 22 | Assert.AreEqual( 3, aMap.PropertyMaps.Count ); 23 | Assert.AreEqual( 0, aMap.PropertyMaps[0].Data.Index ); 24 | Assert.AreEqual( 1, aMap.PropertyMaps[1].Data.Index ); 25 | Assert.AreEqual( 2, aMap.PropertyMaps[2].Data.Index ); 26 | Assert.AreEqual( true, aMap.PropertyMaps[2].Data.Ignore ); 27 | 28 | Assert.AreEqual( 1, aMap.ReferenceMaps.Count ); 29 | } 30 | 31 | private class A 32 | { 33 | public int One { get; set; } 34 | 35 | public int Two { get; set; } 36 | 37 | public int Three { get; set; } 38 | 39 | public B B { get; set; } 40 | } 41 | 42 | private class B 43 | { 44 | public int Four { get; set; } 45 | 46 | public int Five { get; set; } 47 | 48 | public int Six { get; set; } 49 | } 50 | 51 | private sealed class AMap : CsvClassMap 52 | { 53 | public AMap() 54 | { 55 | AutoMap(); 56 | Map( m => m.Three ).Ignore(); 57 | } 58 | } 59 | 60 | private sealed class BMap : CsvClassMap 61 | { 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/CsvHelper/Configuration/CsvConfigurationException.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | 7 | namespace CsvHelper.Configuration 8 | { 9 | /// 10 | /// Represents configuration errors that occur. 11 | /// 12 | public class CsvConfigurationException : CsvHelperException 13 | { 14 | /// 15 | /// Initializes a new instance of the class. 16 | /// 17 | public CsvConfigurationException() {} 18 | 19 | /// 20 | /// Initializes a new instance of the class 21 | /// with a specified error message. 22 | /// 23 | /// The message that describes the error. 24 | public CsvConfigurationException( string message ) : base( message ) {} 25 | 26 | /// 27 | /// Initializes a new instance of the class 28 | /// with a specified error message and a reference to the inner exception that 29 | /// is the cause of this exception. 30 | /// 31 | /// The error message that explains the reason for the exception. 32 | /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. 33 | public CsvConfigurationException( string message, Exception innerException ) : base( message, innerException ) { } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CsvHelper/Configuration/CsvPropertyReferenceMapData.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.Reflection; 6 | 7 | namespace CsvHelper.Configuration 8 | { 9 | /// 10 | /// The configuration data for the reference map. 11 | /// 12 | public class CsvPropertyReferenceMapData 13 | { 14 | private string prefix; 15 | 16 | /// 17 | /// Gets or sets the header prefix to use. 18 | /// 19 | public virtual string Prefix 20 | { 21 | get { return prefix; } 22 | set 23 | { 24 | prefix = value; 25 | foreach( var propertyMap in Mapping.PropertyMaps ) 26 | { 27 | propertyMap.Data.Names.Prefix = value; 28 | } 29 | } 30 | } 31 | 32 | /// 33 | /// Gets the that the data 34 | /// is associated with. 35 | /// 36 | public virtual MemberInfo Member { get; private set; } 37 | 38 | /// 39 | /// Gets the mapping this is a reference for. 40 | /// 41 | public CsvClassMap Mapping { get; private set; } 42 | 43 | /// 44 | /// Initializes a new instance of the class. 45 | /// 46 | /// The property/field. 47 | /// The mapping this is a reference for. 48 | public CsvPropertyReferenceMapData( MemberInfo member, CsvClassMap mapping ) 49 | { 50 | Member = member; 51 | Mapping = mapping; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/CsvTypeConverterException.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | 7 | namespace CsvHelper.TypeConversion 8 | { 9 | /// 10 | /// Represents errors that occur while reading a CSV file. 11 | /// 12 | public class CsvTypeConverterException : CsvHelperException 13 | { 14 | /// 15 | /// Initializes a new instance of the class. 16 | /// 17 | public CsvTypeConverterException() {} 18 | 19 | /// 20 | /// Initializes a new instance of the class 21 | /// with a specified error message. 22 | /// 23 | /// The message that describes the error. 24 | public CsvTypeConverterException( string message ) : base( message ) {} 25 | 26 | /// 27 | /// Initializes a new instance of the class 28 | /// with a specified error message and a reference to the inner exception that 29 | /// is the cause of this exception. 30 | /// 31 | /// The error message that explains the reason for the exception. 32 | /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. 33 | public CsvTypeConverterException( string message, Exception innerException ) : base( message, innerException ) { } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/CsvHelper/ReflectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using System.Linq.Expressions; 4 | 5 | namespace CsvHelper 6 | { 7 | /// 8 | /// Extensions to help with reflection. 9 | /// 10 | public static class ReflectionExtensions 11 | { 12 | /// 13 | /// Gets the type from the property/field. 14 | /// 15 | /// The member to get the type from. 16 | /// The type. 17 | public static Type MemberType( this MemberInfo member ) 18 | { 19 | var property = member as PropertyInfo; 20 | if( property != null ) 21 | { 22 | return property.PropertyType; 23 | } 24 | 25 | var field = member as FieldInfo; 26 | if( field != null ) 27 | { 28 | return field.FieldType; 29 | } 30 | 31 | throw new InvalidOperationException( "Member is not a property or a field." ); 32 | } 33 | 34 | /// 35 | /// Gets a member expression for the property/field. 36 | /// 37 | /// The member to get the expression for. 38 | /// The member expression. 39 | /// The member expression. 40 | public static MemberExpression GetMemberExpression( this MemberInfo member, Expression expression ) 41 | { 42 | var property = member as PropertyInfo; 43 | if( property != null ) 44 | { 45 | return Expression.Property( expression, property ); 46 | } 47 | 48 | var field = member as FieldInfo; 49 | if( field != null ) 50 | { 51 | return Expression.Field( expression, field ); 52 | } 53 | 54 | throw new InvalidOperationException( "Member is not a property or a field." ); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/IDictionaryGenericConverter.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using CsvHelper.Configuration; 6 | 7 | namespace CsvHelper.TypeConversion 8 | { 9 | /// 10 | /// Converts an to and from a . 11 | /// 12 | public class IDictionaryGenericConverter : IDictionaryConverter 13 | { 14 | /// 15 | /// Converts the string to an object. 16 | /// 17 | /// The string to convert to an object. 18 | /// The for the current record. 19 | /// The for the property/field being created. 20 | /// The object created from the string. 21 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 22 | { 23 | var keyType = propertyMapData.Member.MemberType().GetGenericArguments()[0]; 24 | var valueType = propertyMapData.Member.MemberType().GetGenericArguments()[1]; 25 | var dictionaryType = typeof( Dictionary<,> ); 26 | dictionaryType = dictionaryType.MakeGenericType( keyType, valueType ); 27 | var dictionary = (IDictionary)ReflectionHelper.CreateInstance( dictionaryType ); 28 | 29 | var indexEnd = propertyMapData.IndexEnd < propertyMapData.Index 30 | ? row.CurrentRecord.Length - 1 31 | : propertyMapData.IndexEnd; 32 | 33 | for( var i = propertyMapData.Index; i <= indexEnd; i++ ) 34 | { 35 | var field = row.GetField( valueType, i ); 36 | 37 | dictionary.Add( row.FieldHeaders[i], field ); 38 | } 39 | 40 | return dictionary; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/CsvHelper/CsvMissingFieldException.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | 7 | namespace CsvHelper 8 | { 9 | /// 10 | /// Represents an error caused because a field is missing 11 | /// in the header while reading a CSV file. 12 | /// 13 | public class CsvMissingFieldException : CsvReaderException 14 | { 15 | /// 16 | /// Initializes a new instance of the class. 17 | /// 18 | public CsvMissingFieldException() {} 19 | 20 | /// 21 | /// Initializes a new instance of the class 22 | /// with a specified error message. 23 | /// 24 | /// The message that describes the error. 25 | public CsvMissingFieldException( string message ) : base( message ) {} 26 | 27 | /// 28 | /// Initializes a new instance of the class 29 | /// with a specified error message and a reference to the inner exception that 30 | /// is the cause of this exception. 31 | /// 32 | /// The error message that explains the reason for the exception. 33 | /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. 34 | public CsvMissingFieldException( string message, Exception innerException ) : base( message, innerException ) { } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Mocks/ParserMock.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | 6 | using System.Collections; 7 | using System.Collections.Generic; 8 | using System.IO; 9 | using System.Linq; 10 | using CsvHelper.Configuration; 11 | 12 | namespace CsvHelper.Tests.Mocks 13 | { 14 | public class ParserMock : ICsvParser, IEnumerable 15 | { 16 | private readonly Queue rows; 17 | 18 | public void Dispose() 19 | { 20 | } 21 | 22 | public TextReader TextReader { get; } 23 | public ICsvParserConfiguration Configuration { get; private set; } 24 | public int FieldCount { get; private set; } 25 | public long CharPosition { get; private set; } 26 | public long BytePosition { get; private set; } 27 | public int Row { get; private set; } 28 | public int RawRow { get; private set; } 29 | public string RawRecord { get; private set; } 30 | 31 | public ParserMock() 32 | { 33 | Configuration = new CsvConfiguration(); 34 | rows = new Queue(); 35 | } 36 | 37 | public ParserMock( Queue rows ) 38 | { 39 | Configuration = new CsvConfiguration(); 40 | this.rows = rows; 41 | } 42 | 43 | public string[] Read() 44 | { 45 | Row++; 46 | return rows.Dequeue(); 47 | } 48 | 49 | public void Add( params string[] row ) 50 | { 51 | rows.Enqueue( row ); 52 | } 53 | 54 | public IEnumerator GetEnumerator() 55 | { 56 | return rows.GetEnumerator(); 57 | } 58 | 59 | IEnumerator IEnumerable.GetEnumerator() 60 | { 61 | return GetEnumerator(); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/CsvHelper/ICsvParser.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.IO; 7 | using CsvHelper.Configuration; 8 | 9 | namespace CsvHelper 10 | { 11 | /// 12 | /// Defines methods used the parse a CSV file. 13 | /// 14 | public interface ICsvParser : IDisposable 15 | { 16 | /// 17 | /// Gets the . 18 | /// 19 | TextReader TextReader { get; } 20 | 21 | /// 22 | /// Gets the configuration. 23 | /// 24 | ICsvParserConfiguration Configuration { get; } 25 | 26 | /// 27 | /// Gets the character position that the parser is currently on. 28 | /// 29 | long CharPosition { get; } 30 | 31 | /// 32 | /// Gets the byte position that the parser is currently on. 33 | /// 34 | long BytePosition { get; } 35 | 36 | /// 37 | /// Gets the row of the CSV file that the parser is currently on. 38 | /// 39 | int Row { get; } 40 | 41 | /// 42 | /// Gets the row of the CSV file that the parser is currently on. 43 | /// This is the actual file row. 44 | /// 45 | int RawRow { get; } 46 | 47 | /// 48 | /// Gets the raw row for the current record that was parsed. 49 | /// 50 | string RawRecord { get; } 51 | 52 | /// 53 | /// Reads a record from the CSV file. 54 | /// 55 | /// A of fields for the record read. 56 | string[] Read(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/TypeConversion/ByteConverterTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Globalization; 7 | using CsvHelper.Configuration; 8 | using CsvHelper.TypeConversion; 9 | using Microsoft.VisualStudio.TestTools.UnitTesting; 10 | 11 | namespace CsvHelper.Tests.TypeConversion 12 | { 13 | [TestClass] 14 | public class ByteConverterTests 15 | { 16 | [TestMethod] 17 | public void ConvertToStringTest() 18 | { 19 | var converter = new ByteConverter(); 20 | var propertyMapData = new CsvPropertyMapData( null ) 21 | { 22 | TypeConverter = converter, 23 | TypeConverterOptions = { CultureInfo = CultureInfo.CurrentCulture } 24 | }; 25 | 26 | Assert.AreEqual( "123", converter.ConvertToString( (byte)123, null, propertyMapData ) ); 27 | 28 | Assert.AreEqual( "", converter.ConvertToString( null, null, propertyMapData ) ); 29 | } 30 | 31 | [TestMethod] 32 | public void ConvertFromStringTest() 33 | { 34 | var converter = new ByteConverter(); 35 | 36 | var propertyMapData = new CsvPropertyMapData( null ); 37 | propertyMapData.TypeConverterOptions.CultureInfo = CultureInfo.CurrentCulture; 38 | 39 | Assert.AreEqual( (byte)123, converter.ConvertFromString( "123", null, propertyMapData ) ); 40 | Assert.AreEqual( (byte)123, converter.ConvertFromString( " 123 ", null, propertyMapData ) ); 41 | 42 | try 43 | { 44 | converter.ConvertFromString( null, null, propertyMapData ); 45 | Assert.Fail(); 46 | } 47 | catch( CsvTypeConverterException ) 48 | { 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/DateTimeConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Globalization; 7 | using CsvHelper.Configuration; 8 | 9 | namespace CsvHelper.TypeConversion 10 | { 11 | /// 12 | /// Converts a to and from a . 13 | /// 14 | public class DateTimeConverter : DefaultTypeConverter 15 | { 16 | /// 17 | /// Converts the string to an object. 18 | /// 19 | /// The string to convert to an object. 20 | /// The for the current record. 21 | /// The for the property/field being created. 22 | /// The object created from the string. 23 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 24 | { 25 | if( text == null ) 26 | { 27 | return base.ConvertFromString( null, row, propertyMapData ); 28 | } 29 | 30 | var formatProvider = (IFormatProvider)propertyMapData.TypeConverterOptions.CultureInfo.GetFormat( typeof( DateTimeFormatInfo ) ) ?? propertyMapData.TypeConverterOptions.CultureInfo; 31 | var dateTimeStyle = propertyMapData.TypeConverterOptions.DateTimeStyle ?? DateTimeStyles.None; 32 | 33 | return string.IsNullOrEmpty( propertyMapData.TypeConverterOptions.Format ) 34 | ? DateTime.Parse( text, formatProvider, dateTimeStyle ) 35 | : DateTime.ParseExact( text, propertyMapData.TypeConverterOptions.Format, formatProvider, dateTimeStyle ); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/DateTimeOffsetConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | 6 | using System; 7 | using System.Globalization; 8 | using CsvHelper.Configuration; 9 | 10 | namespace CsvHelper.TypeConversion 11 | { 12 | /// 13 | /// Converts a to and from a . 14 | /// 15 | public class DateTimeOffsetConverter : DefaultTypeConverter 16 | { 17 | /// 18 | /// Converts the string to an object. 19 | /// 20 | /// The string to convert to an object. 21 | /// The for the current record. 22 | /// The for the property/field being created. 23 | /// The object created from the string. 24 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 25 | { 26 | if( text == null ) 27 | { 28 | return base.ConvertFromString( null, row, propertyMapData ); 29 | } 30 | 31 | var formatProvider = (IFormatProvider)propertyMapData.TypeConverterOptions.CultureInfo.GetFormat( typeof( DateTimeFormatInfo ) ) ?? propertyMapData.TypeConverterOptions.CultureInfo; 32 | var dateTimeStyle = propertyMapData.TypeConverterOptions.DateTimeStyle ?? DateTimeStyles.None; 33 | 34 | return string.IsNullOrEmpty( propertyMapData.TypeConverterOptions.Format ) 35 | ? DateTimeOffset.Parse( text, formatProvider, dateTimeStyle ) 36 | : DateTimeOffset.ParseExact( text, propertyMapData.TypeConverterOptions.Format, formatProvider, dateTimeStyle ); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/TimeSpanConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Globalization; 7 | using CsvHelper.Configuration; 8 | 9 | namespace CsvHelper.TypeConversion 10 | { 11 | /// 12 | /// Converts a to and from a . 13 | /// 14 | public class TimeSpanConverter : DefaultTypeConverter 15 | { 16 | /// 17 | /// Converts the string to an object. 18 | /// 19 | /// The string to convert to an object. 20 | /// The for the current record. 21 | /// The for the property/field being created. 22 | /// The object created from the string. 23 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 24 | { 25 | var formatProvider = (IFormatProvider)propertyMapData.TypeConverterOptions.CultureInfo; 26 | 27 | TimeSpan span; 28 | 29 | var timeSpanStyle = propertyMapData.TypeConverterOptions.TimeSpanStyle ?? TimeSpanStyles.None; 30 | if( !string.IsNullOrEmpty( propertyMapData.TypeConverterOptions.Format ) && TimeSpan.TryParseExact( text, propertyMapData.TypeConverterOptions.Format, formatProvider, timeSpanStyle, out span ) ) 31 | { 32 | return span; 33 | } 34 | 35 | if( string.IsNullOrEmpty( propertyMapData.TypeConverterOptions.Format ) && TimeSpan.TryParse( text, formatProvider, out span ) ) 36 | { 37 | return span; 38 | } 39 | 40 | return base.ConvertFromString( text, row, propertyMapData ); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /docs/Content/Welcome.aml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | CSV Helper is a .NET library for reading and writing CSV files. 7 | CSV Helper was written with simplicity in mind, and therefore has minimal 8 | setup needed to start using. 9 | 10 | 11 | 12 |
13 | Features 14 | 15 | 16 | 17 | Simple and easy to use. 18 | Parsing engine that can be used separate from reading. 19 | Manually read records. 20 | Automatically read records and populate custom class objects. 21 | Manually write records. 22 | Automatically write records from custom class objects. 23 | 24 | 25 | RFC 4180 26 | http://www.rfc-editor.org/rfc/rfc4180.txt 27 | _blank 28 | 29 | Compliant. 30 | 31 | 32 | 33 | 34 |
35 | 36 | 37 | 38 | RFC 4180 39 | http://www.rfc-editor.org/rfc/rfc4180.txt 40 | _blank 41 | 42 | 43 | 44 | CSV File Format 45 | http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm 46 | _blank 47 | 48 | 49 |
50 |
-------------------------------------------------------------------------------- /src/CsvHelper.Tests/RecordBuilderTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Microsoft.VisualStudio.TestTools.UnitTesting; 7 | 8 | namespace CsvHelper.Tests 9 | { 10 | [TestClass] 11 | public class RecordBuilderTests 12 | { 13 | [TestMethod] 14 | public void SetsDefaultCapacityInDefaultConstructorTest() 15 | { 16 | var rb = new RecordBuilder(); 17 | Assert.AreEqual( 16, rb.Capacity ); 18 | } 19 | 20 | [TestMethod] 21 | public void SetsDefaultCapacityWhenZeroCapacityIsGivenInConstructorTest() 22 | { 23 | var rb = new RecordBuilder( 0 ); 24 | Assert.AreEqual( 16, rb.Capacity ); 25 | } 26 | 27 | [TestMethod] 28 | public void SetsCapacityWhenGivenInConstructorTest() 29 | { 30 | var rb = new RecordBuilder( 1 ); 31 | Assert.AreEqual( 1, rb.Capacity ); 32 | } 33 | 34 | [TestMethod] 35 | public void ResizeTest() 36 | { 37 | var rb = new RecordBuilder( 2 ); 38 | 39 | rb.Add( "1" ); 40 | Assert.AreEqual( 1, rb.Length ); 41 | Assert.AreEqual( 2, rb.Capacity ); 42 | 43 | rb.Add( "2" ); 44 | Assert.AreEqual( 2, rb.Length ); 45 | Assert.AreEqual( 2, rb.Capacity ); 46 | 47 | rb.Add( "3" ); 48 | Assert.AreEqual( 3, rb.Length ); 49 | Assert.AreEqual( 4, rb.Capacity ); 50 | } 51 | 52 | [TestMethod] 53 | public void ClearTest() 54 | { 55 | var rb = new RecordBuilder( 1 ); 56 | rb.Add( "1" ); 57 | rb.Add( "2" ); 58 | rb.Clear(); 59 | var array = rb.ToArray(); 60 | 61 | Assert.AreEqual( 0, rb.Length ); 62 | Assert.AreEqual( 2, rb.Capacity ); 63 | Assert.AreEqual( 0, array.Length ); 64 | } 65 | 66 | [TestMethod] 67 | public void ToArrayTest() 68 | { 69 | var rb = new RecordBuilder(); 70 | 71 | var array = rb.ToArray(); 72 | Assert.AreEqual( 0, array.Length ); 73 | 74 | rb.Add( "1" ); 75 | array = rb.ToArray(); 76 | Assert.AreEqual( 1, array.Length ); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/ReferenceMappingIndexTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Collections; 7 | using System.Collections.Generic; 8 | using System.IO; 9 | using System.Linq; 10 | using System.Text; 11 | using CsvHelper.Configuration; 12 | using CsvHelper.Tests.Mocks; 13 | using Microsoft.VisualStudio.TestTools.UnitTesting; 14 | 15 | namespace CsvHelper.Tests 16 | { 17 | [TestClass] 18 | public class ReferenceMappingIndexTests 19 | { 20 | [TestMethod] 21 | public void MapByIndexTest() 22 | { 23 | var data = new List 24 | { 25 | new[] { "0", "1" }, 26 | new[] { "2", "3" }, 27 | null, 28 | }; 29 | var queue = new Queue( data ); 30 | var parserMock = new ParserMock( queue ); 31 | 32 | var csv = new CsvReader( parserMock ); 33 | csv.Configuration.HasHeaderRecord = false; 34 | csv.Configuration.RegisterClassMap(); 35 | 36 | var records = csv.GetRecords
().ToList(); 37 | Assert.AreEqual( 1, records[0].Id ); 38 | Assert.AreEqual( 0, records[0].B.Id ); 39 | Assert.AreEqual( 3, records[1].Id ); 40 | Assert.AreEqual( 2, records[1].B.Id ); 41 | } 42 | 43 | private class A 44 | { 45 | public int Id { get; set; } 46 | 47 | public B B { get; set; } 48 | } 49 | 50 | private class B 51 | { 52 | public int Id { get; set; } 53 | } 54 | 55 | private sealed class AMap : CsvClassMap 56 | { 57 | public AMap() 58 | { 59 | Map( m => m.Id ).Index( 1 ); 60 | References( m => m.B ); 61 | } 62 | } 63 | 64 | private sealed class BMap : CsvClassMap 65 | { 66 | public BMap() 67 | { 68 | Map( m => m.Id ).Index( 0 ); 69 | } 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/TypeConversion/CharConverterTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Globalization; 7 | using CsvHelper.Configuration; 8 | using CsvHelper.TypeConversion; 9 | using Microsoft.VisualStudio.TestTools.UnitTesting; 10 | 11 | namespace CsvHelper.Tests.TypeConversion 12 | { 13 | [TestClass] 14 | public class CharConverterTests 15 | { 16 | [TestMethod] 17 | public void ConvertToStringTest() 18 | { 19 | var converter = new CharConverter(); 20 | var propertyMapData = new CsvPropertyMapData( null ) 21 | { 22 | TypeConverter = converter, 23 | TypeConverterOptions = { CultureInfo = CultureInfo.CurrentCulture } 24 | }; 25 | 26 | Assert.AreEqual( "a", converter.ConvertToString( 'a', null, propertyMapData ) ); 27 | 28 | Assert.AreEqual( "True", converter.ConvertToString( true, null, propertyMapData ) ); 29 | 30 | Assert.AreEqual( "", converter.ConvertToString( null, null, propertyMapData ) ); 31 | } 32 | 33 | [TestMethod] 34 | public void ConvertFromStringTest() 35 | { 36 | var converter = new CharConverter(); 37 | 38 | var propertyMapData = new CsvPropertyMapData( null ); 39 | propertyMapData.TypeConverterOptions.CultureInfo = CultureInfo.CurrentCulture; 40 | 41 | Assert.AreEqual( 'a', converter.ConvertFromString( "a", null, propertyMapData ) ); 42 | Assert.AreEqual( 'a', converter.ConvertFromString( " a ", null, propertyMapData ) ); 43 | Assert.AreEqual( ' ', converter.ConvertFromString( " ", null, propertyMapData ) ); 44 | 45 | try 46 | { 47 | converter.ConvertFromString( null, null, propertyMapData ); 48 | Assert.Fail(); 49 | } 50 | catch( CsvTypeConverterException ) 51 | { 52 | } 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/EnumConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Reflection; 7 | using CsvHelper.Configuration; 8 | 9 | namespace CsvHelper.TypeConversion 10 | { 11 | /// 12 | /// Converts an to and from a . 13 | /// 14 | public class EnumConverter : DefaultTypeConverter 15 | { 16 | private readonly Type type; 17 | 18 | /// 19 | /// Creates a new for the given . 20 | /// 21 | /// The type of the Enum. 22 | public EnumConverter( Type type ) 23 | { 24 | var isAssignableFrom = typeof( Enum ).GetTypeInfo().IsAssignableFrom( type.GetTypeInfo() ); 25 | if( !typeof( Enum ).IsAssignableFrom( type ) ) 26 | { 27 | throw new ArgumentException( $"'{type.FullName}' is not an Enum." ); 28 | } 29 | 30 | this.type = type; 31 | } 32 | 33 | /// 34 | /// Converts the string to an object. 35 | /// 36 | /// The string to convert to an object. 37 | /// The for the current record. 38 | /// The for the property/field being created. 39 | /// The object created from the string. 40 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 41 | { 42 | try 43 | { 44 | return Enum.Parse( type, text, true ); 45 | } 46 | catch 47 | { 48 | return base.ConvertFromString( text, row, propertyMapData ); 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/DynamicProxyTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Collections.Generic; 7 | using System.IO; 8 | using System.Linq; 9 | using System.Text; 10 | using CsvHelper.Configuration; 11 | using Microsoft.VisualStudio.TestTools.UnitTesting; 12 | 13 | namespace CsvHelper.Tests 14 | { 15 | [TestClass] 16 | public class DynamicProxyTests 17 | { 18 | [TestMethod] 19 | public void WriteDynamicProxyObjectTest() 20 | { 21 | var list = new List(); 22 | var proxyGenerator = new Castle.DynamicProxy.ProxyGenerator(); 23 | for( var i = 0; i < 1; i++ ) 24 | { 25 | var proxy = proxyGenerator.CreateClassProxy(); 26 | proxy.Id = i + 1; 27 | proxy.Name = "name" + proxy.Id; 28 | list.Add( proxy ); 29 | } 30 | 31 | using( var stream = new MemoryStream() ) 32 | using( var reader = new StreamReader( stream ) ) 33 | using( var writer = new StreamWriter( stream ) ) 34 | using( var csv = new CsvWriter( writer ) ) 35 | { 36 | csv.Configuration.RegisterClassMap(); 37 | csv.WriteRecords( list ); 38 | writer.Flush(); 39 | stream.Position = 0; 40 | 41 | var data = reader.ReadToEnd(); 42 | var expected = new StringBuilder(); 43 | expected.AppendLine( "id,name" ); 44 | expected.AppendLine( "1,name1" ); 45 | 46 | Assert.AreEqual( expected.ToString(), data ); 47 | } 48 | } 49 | 50 | public class TestClass 51 | { 52 | public int Id { get; set; } 53 | 54 | public string Name { get; set; } 55 | } 56 | 57 | private sealed class TestClassMap : CsvClassMap 58 | { 59 | public TestClassMap() 60 | { 61 | Map( m => m.Id ).Name( "id" ); 62 | Map( m => m.Name ).Name( "name" ); 63 | } 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Writing/DynamicTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Dynamic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | 9 | namespace CsvHelper.Tests.Writing 10 | { 11 | [TestClass] 12 | public class DynamicTests 13 | { 14 | [TestMethod] 15 | public void WriteDynamicExpandoObjectsTest() 16 | { 17 | using( var stream = new MemoryStream() ) 18 | using( var reader = new StreamReader( stream ) ) 19 | using( var writer = new StreamWriter( stream ) ) 20 | using( var csv = new CsvWriter( writer ) ) 21 | { 22 | var list = new List(); 23 | dynamic obj = new ExpandoObject(); 24 | obj.Id = 1; 25 | obj.Name = "one"; 26 | list.Add( obj ); 27 | 28 | obj = new ExpandoObject(); 29 | obj.Id = 2; 30 | obj.Name = "two"; 31 | list.Add( obj ); 32 | 33 | csv.WriteRecords( list ); 34 | writer.Flush(); 35 | stream.Position = 0; 36 | 37 | var expected = "Id,Name\r\n"; 38 | expected += "1,one\r\n"; 39 | expected += "2,two\r\n"; 40 | 41 | Assert.AreEqual( expected, reader.ReadToEnd() ); 42 | } 43 | } 44 | 45 | [TestMethod] 46 | public void WriteDynamicExpandoObjectTest() 47 | { 48 | using( var stream = new MemoryStream() ) 49 | using( var reader = new StreamReader( stream ) ) 50 | using( var writer = new StreamWriter( stream ) ) 51 | using( var csv = new CsvWriter( writer ) ) 52 | { 53 | dynamic obj = new ExpandoObject(); 54 | obj.Id = 1; 55 | obj.Name = "one"; 56 | 57 | csv.WriteRecord( obj ); 58 | csv.NextRecord(); 59 | 60 | obj = new ExpandoObject(); 61 | obj.Id = 2; 62 | obj.Name = "two"; 63 | 64 | csv.WriteRecord( obj ); 65 | csv.NextRecord(); 66 | 67 | writer.Flush(); 68 | stream.Position = 0; 69 | 70 | var expected = "Id,Name\r\n"; 71 | expected += "1,one\r\n"; 72 | expected += "2,two\r\n"; 73 | 74 | Assert.AreEqual( expected, reader.ReadToEnd() ); 75 | } 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/IEnumerableGenericConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Reflection; 6 | using CsvHelper.Configuration; 7 | 8 | namespace CsvHelper.TypeConversion 9 | { 10 | /// 11 | /// Converts an to and from a . 12 | /// 13 | public class IEnumerableGenericConverter : IEnumerableConverter 14 | { 15 | /// 16 | /// Converts the string to an object. 17 | /// 18 | /// The string to convert to an object. 19 | /// The for the current record. 20 | /// The for the property/field being created. 21 | /// The object created from the string. 22 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 23 | { 24 | var type = propertyMapData.Member.MemberType().GetGenericArguments()[0]; 25 | var listType = typeof( List<> ); 26 | listType = listType.MakeGenericType( type ); 27 | var list = (IList)ReflectionHelper.CreateInstance( listType ); 28 | 29 | if( propertyMapData.IsNameSet || row.Configuration.HasHeaderRecord && !propertyMapData.IsIndexSet ) 30 | { 31 | // Use the name. 32 | var nameIndex = 0; 33 | while( true ) 34 | { 35 | object field; 36 | if( !row.TryGetField( type, propertyMapData.Names.FirstOrDefault(), nameIndex, out field ) ) 37 | { 38 | break; 39 | } 40 | 41 | list.Add( field ); 42 | nameIndex++; 43 | } 44 | } 45 | else 46 | { 47 | // Use the index. 48 | var indexEnd = propertyMapData.IndexEnd < propertyMapData.Index 49 | ? row.CurrentRecord.Length - 1 50 | : propertyMapData.IndexEnd; 51 | 52 | for( var i = propertyMapData.Index; i <= indexEnd; i++ ) 53 | { 54 | var field = row.GetField( type, i ); 55 | 56 | list.Add( field ); 57 | } 58 | } 59 | 60 | return list; 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/CsvReaderDefaultValueTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Diagnostics; 8 | using System.Globalization; 9 | using System.IO; 10 | using System.Linq; 11 | using System.Text; 12 | using CsvHelper.Configuration; 13 | using CsvHelper.Tests.Mocks; 14 | using CsvHelper.TypeConversion; 15 | using Microsoft.VisualStudio.TestTools.UnitTesting; 16 | 17 | namespace CsvHelper.Tests 18 | { 19 | [TestClass] 20 | public class CsvReaderDefaultValueTests 21 | { 22 | [TestMethod] 23 | public void DefaultValueTest() 24 | { 25 | using( var stream = new MemoryStream() ) 26 | using( var writer = new StreamWriter( stream ) ) 27 | using( var reader = new StreamReader( stream ) ) 28 | using( var csvReader = new CsvReader( reader ) ) 29 | { 30 | writer.WriteLine( "Id,Name,Order" ); 31 | writer.WriteLine( ",," ); 32 | writer.WriteLine( "2,two,2" ); 33 | writer.WriteLine( ",three," ); 34 | writer.Flush(); 35 | stream.Position = 0; 36 | 37 | csvReader.Configuration.RegisterClassMap(); 38 | 39 | var records = csvReader.GetRecords().ToList(); 40 | 41 | var record = records[0]; 42 | Assert.AreEqual( -1, record.Id ); 43 | Assert.AreEqual( null, record.Name ); 44 | Assert.AreEqual( -2, record.Order ); 45 | 46 | record = records[1]; 47 | Assert.AreEqual( 2, record.Id ); 48 | Assert.AreEqual( "two", record.Name ); 49 | } 50 | } 51 | 52 | private class Test 53 | { 54 | public int Id { get; set; } 55 | 56 | public string Name { get; set; } 57 | 58 | public int Order { get; set; } 59 | } 60 | 61 | private sealed class TestMap : CsvClassMap 62 | { 63 | public TestMap() 64 | { 65 | Map( m => m.Id ).Default( -1 ); 66 | Map( m => m.Name ).Default( (string)null ); 67 | Map( m => m.Order ).Default( -2 ); 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/CollectionGenericConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.ObjectModel; 4 | using System.Linq; 5 | using System.Reflection; 6 | using CsvHelper.Configuration; 7 | 8 | namespace CsvHelper.TypeConversion 9 | { 10 | /// 11 | /// Converts a to and from a . 12 | /// 13 | public class CollectionGenericConverter : IEnumerableConverter 14 | { 15 | /// 16 | /// Converts the string to an object. 17 | /// 18 | /// The string to convert to an object. 19 | /// The for the current record. 20 | /// The for the property/field being created. 21 | /// The object created from the string. 22 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 23 | { 24 | // Since we're using the PropertyType here, this converter can be used for multiple types 25 | // as long as they implement IList. 26 | var list = (IList)ReflectionHelper.CreateInstance( propertyMapData.Member.MemberType() ); 27 | var type = propertyMapData.Member.MemberType().GetGenericArguments()[0]; 28 | 29 | if( propertyMapData.IsNameSet || row.Configuration.HasHeaderRecord && !propertyMapData.IsIndexSet ) 30 | { 31 | // Use the name. 32 | var nameIndex = 0; 33 | while( true ) 34 | { 35 | object field; 36 | if( !row.TryGetField( type, propertyMapData.Names.FirstOrDefault(), nameIndex, out field ) ) 37 | { 38 | break; 39 | } 40 | 41 | list.Add( field ); 42 | nameIndex++; 43 | } 44 | } 45 | else 46 | { 47 | // Use the index. 48 | var indexEnd = propertyMapData.IndexEnd < propertyMapData.Index 49 | ? row.CurrentRecord.Length - 1 50 | : propertyMapData.IndexEnd; 51 | 52 | for( var i = propertyMapData.Index; i <= indexEnd; i++ ) 53 | { 54 | var field = row.GetField( type, i ); 55 | 56 | list.Add( field ); 57 | } 58 | } 59 | 60 | return list; 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Reading/ShouldSkipRecordTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using CsvHelper.Tests.Mocks; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | 9 | namespace CsvHelper.Tests.Reading 10 | { 11 | [TestClass] 12 | public class ShouldSkipRecordTests 13 | { 14 | [TestMethod] 15 | public void SkipEmptyHeaderTest() 16 | { 17 | var rows = new Queue(); 18 | rows.Enqueue( new[] { " " } ); 19 | rows.Enqueue( new[] { "First,Second" } ); 20 | rows.Enqueue( new[] { "1", "2" } ); 21 | var parser = new ParserMock( rows ); 22 | 23 | var csv = new CsvReader( parser ); 24 | csv.Configuration.ShouldSkipRecord = row => row.All( string.IsNullOrWhiteSpace ); 25 | 26 | csv.Read(); 27 | csv.ReadHeader(); 28 | csv.Read(); 29 | Assert.AreEqual( "1", csv.GetField( 0 ) ); 30 | Assert.AreEqual( "2", csv.GetField( 1 ) ); 31 | } 32 | 33 | [TestMethod] 34 | public void SkipEmptyRowTest() 35 | { 36 | var rows = new Queue(); 37 | rows.Enqueue( new[] { "First,Second" } ); 38 | rows.Enqueue( new[] { " " } ); 39 | rows.Enqueue( new[] { "1", "2" } ); 40 | var parser = new ParserMock( rows ); 41 | 42 | var csv = new CsvReader( parser ); 43 | csv.Configuration.ShouldSkipRecord = row => row.All( string.IsNullOrWhiteSpace ); 44 | 45 | csv.Read(); 46 | csv.ReadHeader(); 47 | csv.Read(); 48 | Assert.AreEqual( "1", csv.GetField( 0 ) ); 49 | Assert.AreEqual( "2", csv.GetField( 1 ) ); 50 | } 51 | 52 | [TestMethod] 53 | public void ShouldSkipWithEmptyRows() 54 | { 55 | var rows = new Queue(); 56 | rows.Enqueue( new[] { "First,Second" } ); 57 | rows.Enqueue( new[] { "skipme," } ); 58 | rows.Enqueue( new[] { "" } ); 59 | rows.Enqueue( new[] { "1", "2" } ); 60 | 61 | var parser = new ParserMock( rows ); 62 | 63 | var csv = new CsvReader( parser ); 64 | csv.Configuration.ShouldSkipRecord = row => row[0].StartsWith( "skipme" ); 65 | csv.Configuration.SkipEmptyRecords = true; 66 | 67 | csv.Read(); 68 | csv.Read(); 69 | Assert.AreEqual( "1", csv.GetField( 0 ) ); 70 | Assert.AreEqual( "2", csv.GetField( 1 ) ); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/DefaultTypeConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Globalization; 7 | using CsvHelper.Configuration; 8 | 9 | namespace CsvHelper.TypeConversion 10 | { 11 | /// 12 | /// Converts an to and from a . 13 | /// 14 | public class DefaultTypeConverter : ITypeConverter 15 | { 16 | /// 17 | /// Converts the object to a string. 18 | /// 19 | /// The object to convert to a string. 20 | /// The for the current record. 21 | /// The for the property/field being written. 22 | /// The string representation of the object. 23 | public virtual string ConvertToString( object value, ICsvWriterRow row, CsvPropertyMapData propertyMapData ) 24 | { 25 | if( value == null ) 26 | { 27 | return string.Empty; 28 | } 29 | 30 | var formattable = value as IFormattable; 31 | if( formattable != null ) 32 | { 33 | return formattable.ToString( propertyMapData.TypeConverterOptions.Format, propertyMapData.TypeConverterOptions.CultureInfo ); 34 | } 35 | 36 | return value.ToString(); 37 | } 38 | 39 | /// 40 | /// Converts the string to an object. 41 | /// 42 | /// The string to convert to an object. 43 | /// The for the current record. 44 | /// The for the property/field being created. 45 | /// The object created from the string. 46 | public virtual object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 47 | { 48 | throw new CsvTypeConverterException( "The conversion cannot be performed." ); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/ParserBadDataTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Collections.Generic; 7 | using System.IO; 8 | using System.Linq; 9 | using System.Text; 10 | using Microsoft.VisualStudio.TestTools.UnitTesting; 11 | 12 | namespace CsvHelper.Tests 13 | { 14 | [TestClass] 15 | public class ParserBadDataTests 16 | { 17 | [TestMethod] 18 | public void CallbackTest() 19 | { 20 | using( var stream = new MemoryStream() ) 21 | using( var reader = new StreamReader( stream ) ) 22 | using( var writer = new StreamWriter( stream ) ) 23 | using( var parser = new CsvParser( reader ) ) 24 | { 25 | writer.WriteLine( " a\"bc\",d" ); 26 | writer.WriteLine( "\"a\"\"b\"c \" ,d" ); 27 | writer.WriteLine( "\"a\"\"b\",c" ); 28 | writer.Flush(); 29 | stream.Position = 0; 30 | 31 | string field = null; 32 | parser.Configuration.BadDataCallback = f => field = f; 33 | parser.Read(); 34 | 35 | Assert.IsNotNull( field ); 36 | Assert.AreEqual( " a\"bc\"", field ); 37 | 38 | field = null; 39 | parser.Read(); 40 | Assert.IsNotNull( field ); 41 | Assert.AreEqual( "a\"bc \" ", field ); 42 | 43 | field = null; 44 | parser.Read(); 45 | Assert.IsNull( field ); 46 | } 47 | } 48 | 49 | [TestMethod] 50 | public void ThrowExceptionTest() 51 | { 52 | using( var stream = new MemoryStream() ) 53 | using( var reader = new StreamReader( stream ) ) 54 | using( var writer = new StreamWriter( stream ) ) 55 | using( var parser = new CsvParser( reader ) ) 56 | { 57 | writer.WriteLine( "1,2" ); 58 | writer.WriteLine( " a\"bc\",d" ); 59 | writer.Flush(); 60 | stream.Position = 0; 61 | 62 | parser.Configuration.ThrowOnBadData = true; 63 | parser.Read(); 64 | try 65 | { 66 | parser.Read(); 67 | Assert.Fail( "Failed to throw exception on bad data." ); 68 | } 69 | catch( CsvBadDataException ) { } 70 | } 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/CsvHelper/Configuration/CsvPropertyReferenceMap.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Reflection; 7 | 8 | namespace CsvHelper.Configuration 9 | { 10 | /// 11 | /// Mapping info for a reference property/field mapping to a class. 12 | /// 13 | public class CsvPropertyReferenceMap 14 | { 15 | private readonly CsvPropertyReferenceMapData data; 16 | 17 | /// 18 | /// Gets the property/field reference map data. 19 | /// 20 | public CsvPropertyReferenceMapData Data => data; 21 | 22 | /// 23 | /// Initializes a new instance of the class. 24 | /// 25 | /// The property/field. 26 | /// The to use for the reference map. 27 | public CsvPropertyReferenceMap( MemberInfo member, CsvClassMap mapping ) 28 | { 29 | if( mapping == null ) 30 | { 31 | throw new ArgumentNullException( nameof( mapping ) ); 32 | } 33 | 34 | data = new CsvPropertyReferenceMapData( member, mapping ); 35 | } 36 | 37 | /// 38 | /// Appends a prefix to the header of each field of the reference property/field. 39 | /// 40 | /// The prefix to be prepended to headers of each reference property/field. 41 | /// The current 42 | public CsvPropertyReferenceMap Prefix( string prefix = null ) 43 | { 44 | if( string.IsNullOrEmpty( prefix ) ) 45 | { 46 | prefix = data.Member.Name + "."; 47 | } 48 | 49 | data.Prefix = prefix; 50 | 51 | return this; 52 | } 53 | 54 | /// 55 | /// Get the largest index for the 56 | /// properties/fields and references. 57 | /// 58 | /// The max index. 59 | internal int GetMaxIndex() 60 | { 61 | return data.Mapping.GetMaxIndex(); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/BooleanConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Globalization; 7 | using CsvHelper.Configuration; 8 | 9 | namespace CsvHelper.TypeConversion 10 | { 11 | /// 12 | /// Converts a to and from a . 13 | /// 14 | public class BooleanConverter : DefaultTypeConverter 15 | { 16 | /// 17 | /// Converts the string to an object. 18 | /// 19 | /// The string to convert to an object. 20 | /// The for the current record. 21 | /// The for the property/field being created. 22 | /// The object created from the string. 23 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 24 | { 25 | bool b; 26 | if( bool.TryParse( text, out b ) ) 27 | { 28 | return b; 29 | } 30 | 31 | short sh; 32 | if( short.TryParse( text, out sh ) ) 33 | { 34 | if( sh == 0 ) 35 | { 36 | return false; 37 | } 38 | if( sh == 1 ) 39 | { 40 | return true; 41 | } 42 | } 43 | 44 | var t = ( text ?? string.Empty ).Trim(); 45 | foreach( var trueValue in propertyMapData.TypeConverterOptions.BooleanTrueValues ) 46 | { 47 | if( propertyMapData.TypeConverterOptions.CultureInfo.CompareInfo.Compare( trueValue, t, CompareOptions.IgnoreCase ) == 0 ) 48 | { 49 | return true; 50 | } 51 | } 52 | 53 | foreach( var falseValue in propertyMapData.TypeConverterOptions.BooleanFalseValues ) 54 | { 55 | if( propertyMapData.TypeConverterOptions.CultureInfo.CompareInfo.Compare( falseValue, t, CompareOptions.IgnoreCase ) == 0 ) 56 | { 57 | return false; 58 | } 59 | } 60 | 61 | return base.ConvertFromString( text, row, propertyMapData ); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /docs/Content/Reading/ReadingFields.aml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Reading fields will give you back the field converted into the specified 7 | type using the default T:System.ComponentModel.TypeConverter 8 | for that type, or the specified T:System.ComponentModel.TypeConverter. 9 | You can read by the field's integer position or the column name position. 10 | 11 | 12 | 13 |
14 | Reading Fields 15 | 16 | 17 | All you need to do to read fields is to specify the type you want 18 | and the field will automatically be converted to that type. 19 | 20 | 21 | If you run into a field that can't be auto-converted, you can 22 | specify a 23 | to use. 24 | 25 | 26 | 27 | ( 0 ) + columnSeparator ); 35 | Console.Write( reader.GetField( "Int Column" ) + columnSeparator ); 36 | Console.Write( reader.GetField( 2 ) + columnSeparator ); 37 | Console.WriteLine( reader.GetField( 3, customTypeTypeConverter ) ); 38 | } 39 | } 40 | ]]> 41 | 42 | 43 | 44 |
45 | 46 |
47 | Output 48 | 49 | 50 | 51 | 52 | 53 |
54 | 55 | 56 | 57 | 58 |
59 |
-------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/IDictionaryConverter.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using CsvHelper.Configuration; 5 | 6 | namespace CsvHelper.TypeConversion 7 | { 8 | /// 9 | /// Converts an to and from a . 10 | /// 11 | public class IDictionaryConverter : DefaultTypeConverter 12 | { 13 | /// 14 | /// Converts the object to a string. 15 | /// 16 | /// The object to convert to a string. 17 | /// The for the current record. 18 | /// The for the property/field being written. 19 | /// The string representation of the object. 20 | public override string ConvertToString( object value, ICsvWriterRow row, CsvPropertyMapData propertyMapData ) 21 | { 22 | var dictionary = value as IDictionary; 23 | if( dictionary == null ) 24 | { 25 | return base.ConvertToString( value, row, propertyMapData ); 26 | } 27 | 28 | foreach( DictionaryEntry entry in dictionary ) 29 | { 30 | row.WriteField( entry.Value ); 31 | } 32 | 33 | return null; 34 | } 35 | 36 | /// 37 | /// Converts the string to an object. 38 | /// 39 | /// The string to convert to an object. 40 | /// The for the current record. 41 | /// The for the property/field being created. 42 | /// The object created from the string. 43 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 44 | { 45 | var dictionary = new Dictionary(); 46 | 47 | var indexEnd = propertyMapData.IndexEnd < propertyMapData.Index 48 | ? row.CurrentRecord.Length - 1 49 | : propertyMapData.IndexEnd; 50 | 51 | for( var i = propertyMapData.Index; i <= indexEnd; i++ ) 52 | { 53 | string field; 54 | if( row.TryGetField( i, out field ) ) 55 | { 56 | dictionary.Add( row.FieldHeaders[i], field ); 57 | } 58 | } 59 | 60 | return dictionary; 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/CsvHelper/RecordBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CsvHelper 4 | { 5 | /// 6 | /// Builds CSV records. 7 | /// 8 | public class RecordBuilder 9 | { 10 | private const int DEFAULT_CAPACITY = 16; 11 | private string[] record; 12 | private int position; 13 | private int capacity; 14 | 15 | /// 16 | /// The number of records. 17 | /// 18 | public int Length => position; 19 | 20 | /// 21 | /// The total record capacity. 22 | /// 23 | public int Capacity => capacity; 24 | 25 | /// 26 | /// Creates a new using defaults. 27 | /// 28 | public RecordBuilder() : this( DEFAULT_CAPACITY ) { } 29 | 30 | /// 31 | /// Creatse a new using the given capacity. 32 | /// 33 | /// The initial capacity. 34 | public RecordBuilder( int capacity ) 35 | { 36 | this.capacity = capacity > 0 ? capacity : DEFAULT_CAPACITY; 37 | 38 | record = new string[capacity]; 39 | } 40 | 41 | /// 42 | /// Adds a new field to the . 43 | /// 44 | /// The field to add. 45 | /// The current instance of the . 46 | public virtual RecordBuilder Add( string field ) 47 | { 48 | if( position == record.Length ) 49 | { 50 | capacity = capacity * 2; 51 | Array.Resize( ref record, capacity ); 52 | } 53 | 54 | record[position] = field; 55 | position++; 56 | 57 | return this; 58 | } 59 | 60 | /// 61 | /// Clears the records. 62 | /// 63 | /// The current instance of the . 64 | public virtual RecordBuilder Clear() 65 | { 66 | position = 0; 67 | 68 | return this; 69 | } 70 | 71 | /// 72 | /// Returns the record as an . 73 | /// 74 | /// The record as an . 75 | public virtual string[] ToArray() 76 | { 77 | var array = new string[position]; 78 | Array.Copy( record, array, position ); 79 | 80 | return array; 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/CsvHelper/CsvHelperException.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Collections.Generic; 7 | 8 | namespace CsvHelper 9 | { 10 | /// 11 | /// Represents errors that occur in CsvHelper. 12 | /// 13 | public class CsvHelperException : Exception 14 | { 15 | /// 16 | /// The current row number. 17 | /// 18 | public int Row { get; set; } 19 | 20 | /// 21 | /// The property/field type of the current field. 22 | /// 23 | public Type Type { get; set; } 24 | 25 | /// 26 | /// The index of the current field. 27 | /// 28 | public int FieldIndex { get; set; } 29 | 30 | /// 31 | /// The field name. 32 | /// 33 | public string FieldName { get; set; } 34 | 35 | /// 36 | /// The field value. 37 | /// 38 | public string FieldValue { get; set; } 39 | 40 | /// 41 | /// Initializes a new instance of the class. 42 | /// 43 | public CsvHelperException() {} 44 | 45 | /// 46 | /// Initializes a new instance of the class 47 | /// with a specified error message. 48 | /// 49 | /// The message that describes the error. 50 | public CsvHelperException( string message ) : base( message ) {} 51 | 52 | /// 53 | /// Initializes a new instance of the class 54 | /// with a specified error message and a reference to the inner exception that 55 | /// is the cause of this exception. 56 | /// 57 | /// The error message that explains the reason for the exception. 58 | /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. 59 | public CsvHelperException( string message, Exception innerException ) : base( message, innerException ) { } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/ArrayConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using CsvHelper.Configuration; 6 | 7 | namespace CsvHelper.TypeConversion 8 | { 9 | /// 10 | /// Converts an to and from a . 11 | /// 12 | public class ArrayConverter : IEnumerableConverter 13 | { 14 | /// 15 | /// Converts the string to an object. 16 | /// 17 | /// The string to convert to an object. 18 | /// The for the current record. 19 | /// The for the property/field being created. 20 | /// The object created from the string. 21 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 22 | { 23 | Array array; 24 | var type = propertyMapData.Member.MemberType().GetElementType(); 25 | 26 | if( propertyMapData.IsNameSet || row.Configuration.HasHeaderRecord && !propertyMapData.IsIndexSet ) 27 | { 28 | // Use the name. 29 | var list = new List(); 30 | var nameIndex = 0; 31 | while( true ) 32 | { 33 | object field; 34 | if( !row.TryGetField( type, propertyMapData.Names.FirstOrDefault(), nameIndex, out field ) ) 35 | { 36 | break; 37 | } 38 | 39 | list.Add( field ); 40 | nameIndex++; 41 | } 42 | 43 | array = (Array)ReflectionHelper.CreateInstance( propertyMapData.Member.MemberType(), list.Count ); 44 | for( var i = 0; i < list.Count; i++ ) 45 | { 46 | array.SetValue( list[i], i ); 47 | } 48 | } 49 | else 50 | { 51 | // Use the index. 52 | var indexEnd = propertyMapData.IndexEnd < propertyMapData.Index 53 | ? row.CurrentRecord.Length - 1 54 | : propertyMapData.IndexEnd; 55 | 56 | var arraySize = indexEnd - propertyMapData.Index + 1; 57 | array = (Array)ReflectionHelper.CreateInstance( propertyMapData.Member.MemberType(), arraySize ); 58 | var arrayIndex = 0; 59 | for( var i = propertyMapData.Index; i <= indexEnd; i++ ) 60 | { 61 | array.SetValue( row.GetField( type, i ), arrayIndex ); 62 | arrayIndex++; 63 | } 64 | } 65 | 66 | return array; 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/CsvHelper/CsvHelper.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | A library for reading and writing CSV files. Extremely fast, flexible, and easy to use. Supports reading and writing of custom class objects. 5 | Copyright © 2009-2016 Josh Close and Contributors 6 | CsvHelper 7 | 3.0.0.0 8 | 3.0.0 9 | beta8 10 | Josh Close 11 | netstandard1.3 12 | true 13 | CsvHelper 14 | CsvHelper.snk 15 | true 16 | true 17 | CsvHelper 18 | csv;csvhelper;comma;separated;value;delimited 19 | http://joshclose.github.io/CsvHelper/#change-log 20 | https://raw.github.com/JoshClose/CsvHelper/master/logo/Comma-Small.png 21 | https://github.com/JoshClose/CsvHelper 22 | https://raw.githubusercontent.com/JoshClose/CsvHelper/master/LICENSE.txt 23 | true 24 | 1.6.0 25 | false 26 | false 27 | https://github.com/JoshClose/CsvHelper 28 | git 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | $(DefineConstants);NETSTANDARD 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /docs/Content/CustomTypeConverter.aml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | If you want to read or write a field using different output other than 7 | what the default T:System.ComponentModel.TypeConverter 8 | for that type uses, you can create your own custom 9 | T:System.ComponentModel.TypeConverter. 10 | 11 | 12 | 13 |
14 | Custom Type Converter 15 | 16 | 17 | 18 | For the type converter to work properly, you must override 19 | the CanConvertFrom method for reading, and CanConvertTo 20 | method for writing. 21 | 22 | 23 | 24 | 57 | 58 | 59 | 60 |
61 | 62 | 63 | T:System.ComponentModel.TypeConverter 64 | 65 |
66 |
-------------------------------------------------------------------------------- /src/CsvHelper.Tests/MapPropertyMultipleTimesTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Text; 5 | using CsvHelper.Configuration; 6 | using Microsoft.VisualStudio.TestTools.UnitTesting; 7 | 8 | namespace CsvHelper.Tests 9 | { 10 | [TestClass] 11 | public class MapPropertyMultipleTimesTests 12 | { 13 | [TestMethod] 14 | public void MapProperitesToMultipleFieldsWhenWritingTest() 15 | { 16 | using( var stream = new MemoryStream() ) 17 | using( var reader = new StreamReader( stream ) ) 18 | using( var writer = new StreamWriter( stream ) ) 19 | using( var csv = new CsvWriter( writer ) ) 20 | { 21 | var list = new List 22 | { 23 | new Test { Id = 1, Name = "one" } 24 | }; 25 | 26 | csv.Configuration.RegisterClassMap(); 27 | csv.WriteRecords( list ); 28 | writer.Flush(); 29 | stream.Position = 0; 30 | 31 | var expected = new StringBuilder(); 32 | expected.AppendLine( "Id1,Name1,Id2,Name2" ); 33 | expected.AppendLine( "1,one,1,one" ); 34 | 35 | var result = reader.ReadToEnd(); 36 | 37 | Assert.AreEqual( expected.ToString(), result ); 38 | } 39 | } 40 | 41 | [TestMethod] 42 | public void MapPropertiesToMultipleFieldsWhenReadingTest() 43 | { 44 | // This is not something that anyone should do, but this 45 | // is the expected behavior if they do. 46 | 47 | using( var stream = new MemoryStream() ) 48 | using( var reader = new StreamReader( stream ) ) 49 | using( var writer = new StreamWriter( stream ) ) 50 | using( var csv = new CsvReader( reader ) ) 51 | { 52 | writer.WriteLine( "Id1,Name1,Id2,Name2" ); 53 | writer.WriteLine( "1,one,2,two" ); 54 | writer.Flush(); 55 | stream.Position = 0; 56 | 57 | csv.Configuration.RegisterClassMap(); 58 | var records = csv.GetRecords().ToList(); 59 | 60 | Assert.AreEqual( 2, records[0].Id ); 61 | Assert.AreEqual( "two", records[0].Name ); 62 | } 63 | } 64 | 65 | private class Test 66 | { 67 | public int Id { get; set; } 68 | public string Name { get; set; } 69 | } 70 | 71 | private sealed class TestMap : CsvClassMap 72 | { 73 | public TestMap() 74 | { 75 | Map( m => m.Id ).Name( "Id1" ); 76 | Map( m => m.Name ).Name( "Name1" ); 77 | Map( m => m.Id, false ).Name( "Id2" ); 78 | Map( m => m.Name, false ).Name( "Name2" ); 79 | } 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /README.markdown: -------------------------------------------------------------------------------- 1 | # CsvHelper 2 | 3 | [![Join the chat at https://gitter.im/CsvHelper/Lobby](https://badges.gitter.im/CsvHelper/Lobby.svg)](https://gitter.im/CsvHelper/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) 4 | 5 | A library for reading and writing CSV files. Extremely fast, flexible, and easy to use. Supports reading and writing of custom class objects. 6 | 7 | ## Install 8 | 9 | To install CsvHelper, run the following command in the Package Manager Console 10 | 11 | PM> Install-Package CsvHelper 12 | 13 | ## Documentation 14 | 15 | http://joshclose.github.io/CsvHelper/ 16 | 17 | ## License 18 | 19 | Dual licensed 20 | 21 | Microsoft Public License (MS-PL) 22 | 23 | http://www.opensource.org/licenses/MS-PL 24 | 25 | Apache License, Version 2.0 26 | 27 | http://opensource.org/licenses/Apache-2.0 28 | 29 | ## Contribution 30 | 31 | Want to contribute? Great! Here are a few guidelines. 32 | 33 | 1. If you want to do a feature, post an issue about the feature first. Some features are intentionally left out, some features may already be in the works, or I may have some advice on how I think it should be done. I would feel bad if time was spent on some code that won't be used. 34 | 2. If you want to do a bug fix, it might not be a bad idea to post about it too. I've had the same bug fixed by multiple people at the same time before. 35 | 3. All code should a unit test. If you make a feature, there should be significant tests around the feature. If you do a bug fix, there should be a test specific to that bug so it doesn't happen again. 36 | 4. Pull requests should have a single commit. If you have multiple commits, squash them into a single commit before requesting a pull. 37 | 5. Try and follow the code styling already in place. If you have ReSharper there is a dotsettings file included and things should automatically be formatted for you. 38 | 39 | ## Gifts * 40 | 41 | Several people have asked me to give them a way to gift money for working on the project, so I have made a public Amazon wish list. 42 | In the future I may add a way to gift money through paypal or something similar, but for now I'd rather not recieve cash gifts. 43 | Any gifts are greatly appreciated and I'm still very shocked that people are asking for this. I'm just glad CsvHelper has helped 44 | make working with CSV files easier for people. 45 | 46 | [Amazon Wish List](https://amzn.com/w/36WDXJGN8KQO6) 47 | 48 | * Disclaimer: All gifts go directly to Josh Close and are not considered compensation in any form. 49 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/CsvReaderReferenceMappingPrefixTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2014 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is licensed under the MS-PL 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html 4 | // http://csvhelper.com 5 | using System.IO; 6 | using System.Linq; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | using CsvHelper.Configuration; 9 | 10 | namespace CsvHelper.Tests 11 | { 12 | [TestClass] 13 | public class CsvReaderReferenceMappingPrefixTests 14 | { 15 | [TestMethod] 16 | public void ReferencesWithPrefixTest() 17 | { 18 | using( var stream = new MemoryStream() ) 19 | using( var reader = new StreamReader( stream ) ) 20 | using( var writer = new StreamWriter( stream ) ) 21 | using( var csv = new CsvReader( reader ) ) 22 | { 23 | csv.Configuration.RegisterClassMap(); 24 | 25 | writer.WriteLine( "Id,BPrefix_Id,C.CId" ); 26 | writer.WriteLine( "a1,b1,c1" ); 27 | writer.WriteLine( "a2,b2,c2" ); 28 | writer.WriteLine( "a3,b3,c3" ); 29 | writer.WriteLine( "a4,b4,c4" ); 30 | writer.Flush(); 31 | stream.Position = 0; 32 | 33 | var list = csv.GetRecords().ToList(); 34 | 35 | Assert.IsNotNull( list ); 36 | Assert.AreEqual( 4, list.Count ); 37 | 38 | for( var i = 0; i < 4; i++ ) 39 | { 40 | var rowId = i + 1; 41 | var row = list[i]; 42 | Assert.AreEqual( "a" + rowId, row.Id ); 43 | Assert.AreEqual( "b" + rowId, row.B.Id ); 44 | Assert.AreEqual( "c" + rowId, row.B.C.Id ); 45 | } 46 | } 47 | } 48 | 49 | private class A 50 | { 51 | public string Id { get; set; } 52 | 53 | public B B { get; set; } 54 | } 55 | 56 | private class B 57 | { 58 | public string Id { get; set; } 59 | 60 | public C C { get; set; } 61 | } 62 | 63 | private class C 64 | { 65 | public string Id { get; set; } 66 | } 67 | 68 | private sealed class AMap : CsvClassMap 69 | { 70 | public AMap() 71 | { 72 | Map( m => m.Id ); 73 | References( m => m.B ).Prefix( "BPrefix_" ); 74 | } 75 | } 76 | 77 | private sealed class BMap : CsvClassMap 78 | { 79 | public BMap() 80 | { 81 | Map( m => m.Id ); 82 | References( m => m.C ).Prefix(); 83 | } 84 | } 85 | 86 | private sealed class CMap : CsvClassMap 87 | { 88 | public CMap() 89 | { 90 | Map( m => m.Id ).Name( "CId" ); 91 | } 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/TypeConversion/TimeSpanConverterTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Globalization; 7 | using CsvHelper.Configuration; 8 | using CsvHelper.TypeConversion; 9 | using Microsoft.VisualStudio.TestTools.UnitTesting; 10 | 11 | namespace CsvHelper.Tests.TypeConversion 12 | { 13 | [TestClass] 14 | public class TimeSpanConverterTests 15 | { 16 | [TestMethod] 17 | public void ConvertToStringTest() 18 | { 19 | var converter = new TimeSpanConverter(); 20 | var propertyMapData = new CsvPropertyMapData( null ) 21 | { 22 | TypeConverter = converter, 23 | TypeConverterOptions = { CultureInfo = CultureInfo.CurrentCulture } 24 | }; 25 | 26 | var dateTime = DateTime.Now; 27 | var timeSpan = new TimeSpan( dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond ); 28 | 29 | // Valid conversions. 30 | Assert.AreEqual( timeSpan.ToString(), converter.ConvertToString( timeSpan, null, propertyMapData ) ); 31 | 32 | // Invalid conversions. 33 | Assert.AreEqual( "1", converter.ConvertToString( 1, null, propertyMapData ) ); 34 | Assert.AreEqual( "", converter.ConvertToString( null, null, propertyMapData ) ); 35 | } 36 | 37 | [TestMethod] 38 | public void ComponentModelCompatibilityTest() 39 | { 40 | var converter = new TimeSpanConverter(); 41 | var cmConverter = new System.ComponentModel.TimeSpanConverter(); 42 | 43 | var propertyMapData = new CsvPropertyMapData( null ); 44 | propertyMapData.TypeConverterOptions.CultureInfo = CultureInfo.CurrentCulture; 45 | 46 | try 47 | { 48 | cmConverter.ConvertFromString( "" ); 49 | Assert.Fail(); 50 | } 51 | catch( FormatException ) {} 52 | 53 | try 54 | { 55 | var val = (DateTime)converter.ConvertFromString( "", null, propertyMapData ); 56 | Assert.Fail(); 57 | } 58 | catch( CsvTypeConverterException ) {} 59 | 60 | try 61 | { 62 | cmConverter.ConvertFromString( null ); 63 | Assert.Fail(); 64 | } 65 | catch( NotSupportedException ) { } 66 | 67 | try 68 | { 69 | converter.ConvertFromString( null, null, propertyMapData ); 70 | Assert.Fail(); 71 | } 72 | catch( CsvTypeConverterException ) { } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/EnumerableConverter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Collections; 7 | using System.Globalization; 8 | using CsvHelper.Configuration; 9 | 10 | namespace CsvHelper.TypeConversion 11 | { 12 | /// 13 | /// Throws an exception when used. This is here so that it's apparent 14 | /// that there is no support for type coversion. A custom 15 | /// converter will need to be created to have a field convert to and 16 | /// from an IEnumerable. 17 | /// 18 | public class EnumerableConverter : DefaultTypeConverter 19 | { 20 | /// 21 | /// Throws an exception. 22 | /// 23 | /// The string to convert to an object. 24 | /// The for the current record. 25 | /// The for the property/field being created. 26 | /// The object created from the string. 27 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 28 | { 29 | throw new CsvTypeConverterException( "Converting IEnumerable types is not supported for a single field. " + 30 | "If you want to do this, create your own ITypeConverter and register " + 31 | "it in the TypeConverterFactory by calling AddConverter." ); 32 | } 33 | 34 | /// 35 | /// Throws an exception. 36 | /// 37 | /// The object to convert to a string. 38 | /// The for the current record. 39 | /// The for the property/field being written. 40 | /// The string representation of the object. 41 | public override string ConvertToString( object value, ICsvWriterRow row, CsvPropertyMapData propertyMapData ) 42 | { 43 | throw new CsvTypeConverterException( "Converting IEnumerable types is not supported for a single field. " + 44 | "If you want to do this, create your own ITypeConverter and register " + 45 | "it in the TypeConverterFactory by calling AddConverter." ); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Mappings/SubPropertyMappingTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using CsvHelper.Configuration; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | namespace CsvHelper.Tests.Mappings 11 | { 12 | [TestClass] 13 | public class SubPropertyMappingTests 14 | { 15 | [TestMethod] 16 | public void ReadTest() 17 | { 18 | using( var stream = new MemoryStream() ) 19 | using( var reader = new StreamReader( stream ) ) 20 | using( var writer = new StreamWriter( stream ) ) 21 | using( var csv = new CsvReader( reader ) ) 22 | { 23 | writer.WriteLine( "P3,P1,P2" ); 24 | writer.WriteLine( "p3,p1,p2" ); 25 | writer.Flush(); 26 | stream.Position = 0; 27 | 28 | csv.Configuration.RegisterClassMap(); 29 | var records = csv.GetRecords().ToList(); 30 | 31 | Assert.AreEqual( "p1", records[0].P1 ); 32 | Assert.AreEqual( "p2", records[0].B.P2 ); 33 | Assert.AreEqual( "p3", records[0].B.C.P3 ); 34 | } 35 | } 36 | 37 | [TestMethod] 38 | public void WriteTest() 39 | { 40 | using( var stream = new MemoryStream() ) 41 | using( var reader = new StreamReader( stream ) ) 42 | using( var writer = new StreamWriter( stream ) ) 43 | using( var csv = new CsvWriter( writer ) ) 44 | { 45 | var list = new List() 46 | { 47 | new A 48 | { 49 | P1 = "p1", 50 | B = new B 51 | { 52 | P2 = "p2", 53 | C = new C 54 | { 55 | P3 = "p3" 56 | } 57 | } 58 | } 59 | }; 60 | 61 | csv.Configuration.RegisterClassMap(); 62 | csv.WriteRecords( list ); 63 | writer.Flush(); 64 | stream.Position = 0; 65 | 66 | var expected = "P3,P1,P2\r\n"; 67 | expected += "p3,p1,p2\r\n"; 68 | var result = reader.ReadToEnd(); 69 | 70 | Assert.AreEqual( expected, result ); 71 | } 72 | } 73 | 74 | private class A 75 | { 76 | public string P1 { get; set; } 77 | public B B { get; set; } 78 | } 79 | 80 | private class B 81 | { 82 | public string P2 { get; set; } 83 | public C C { get; set; } 84 | } 85 | 86 | private class C 87 | { 88 | public string P3 { get; set; } 89 | } 90 | 91 | private sealed class AMap : CsvClassMap 92 | { 93 | public AMap() 94 | { 95 | Map( m => m.B.C.P3 ).Index( 0 ); 96 | Map( m => m.P1 ).Index( 1 ); 97 | Map( m => m.B.P2 ).Index( 2 ); 98 | } 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/CsvHelper/TypeConversion/IEnumerableConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using CsvHelper.Configuration; 6 | 7 | namespace CsvHelper.TypeConversion 8 | { 9 | /// 10 | /// Converts an to and from a . 11 | /// 12 | public class IEnumerableConverter : DefaultTypeConverter 13 | { 14 | /// 15 | /// Converts the object to a string. 16 | /// 17 | /// The object to convert to a string. 18 | /// 19 | /// 20 | /// The string representation of the object. 21 | public override string ConvertToString( object value, ICsvWriterRow row, CsvPropertyMapData propertyMapData ) 22 | { 23 | var list = value as IEnumerable; 24 | if( list == null ) 25 | { 26 | return base.ConvertToString( value, row, propertyMapData ); 27 | } 28 | 29 | foreach( var item in list ) 30 | { 31 | row.WriteField( item.ToString() ); 32 | } 33 | 34 | return null; 35 | } 36 | 37 | /// 38 | /// Converts the string to an object. 39 | /// 40 | /// The string to convert to an object. 41 | /// The for the current record. 42 | /// The for the property/field being created. 43 | /// The object created from the string. 44 | public override object ConvertFromString( string text, ICsvReaderRow row, CsvPropertyMapData propertyMapData ) 45 | { 46 | var list = new List(); 47 | 48 | if( propertyMapData.IsNameSet || row.Configuration.HasHeaderRecord && !propertyMapData.IsIndexSet ) 49 | { 50 | // Use the name. 51 | var nameIndex = 0; 52 | while( true ) 53 | { 54 | string field; 55 | if( !row.TryGetField( propertyMapData.Names.FirstOrDefault(), nameIndex, out field ) ) 56 | { 57 | break; 58 | } 59 | 60 | list.Add( field ); 61 | nameIndex++; 62 | } 63 | } 64 | else 65 | { 66 | // Use the index. 67 | var indexEnd = propertyMapData.IndexEnd < propertyMapData.Index 68 | ? row.CurrentRecord.Length - 1 69 | : propertyMapData.IndexEnd; 70 | 71 | for( var i = propertyMapData.Index; i <= indexEnd; i++ ) 72 | { 73 | string field; 74 | if( row.TryGetField( i, out field ) ) 75 | { 76 | list.Add( field ); 77 | } 78 | } 79 | } 80 | 81 | return list; 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/CsvHelper/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | 6 | using System; 7 | using System.Reflection; 8 | using System.Runtime.CompilerServices; 9 | using System.Runtime.InteropServices; 10 | using System.Security; 11 | 12 | // General Information about an assembly is controlled through the following 13 | // set of attributes. Change these attribute values to modify the information 14 | // associated with an assembly. 15 | [assembly: AssemblyProduct( "CsvHelper" )] 16 | //[assembly: AssemblyTitle( "CsvHelper" )] 17 | //[assembly: AssemblyCompany( "Josh Close" )] 18 | //[assembly: AssemblyDescription( "A library for reading and writing CSV files. Extremely fast, flexible, and easy to use. Supports reading and writing of custom class objects." )] 19 | //[assembly: AssemblyConfiguration( "" )] 20 | //[assembly: AssemblyCopyright( "Copyright © Josh Close 2009-2016" )] 21 | //[assembly: AssemblyTrademark( "" )] 22 | //[assembly: AssemblyCulture( "" )] 23 | 24 | // Setting ComVisible to false makes the types in this assembly not visible 25 | // to COM components. If you need to access a type in this assembly from 26 | // COM, set the ComVisible attribute to true on that type. 27 | [assembly: ComVisible( false )] 28 | 29 | // The following GUID is for the ID of the typelib if this project is exposed to COM 30 | [assembly: Guid( "2bff163b-a135-4068-be75-9a9464f3250f" )] 31 | 32 | // Version information for an assembly consists of the following four values: 33 | // 34 | // Major Version 35 | // Minor Version 36 | // Build Number 37 | // Revision 38 | // 39 | // You can specify all the values or you can default the Build and Revision Numbers 40 | // by using the '*' as shown below: 41 | 42 | // DO NOT update this. 43 | //[assembly: AssemblyVersion( "3.0.0.0" )] 44 | 45 | // This is now set from the project.json file. 46 | // Update this. 47 | //[assembly: AssemblyFileVersion( "2.16.0.0" )] 48 | 49 | [assembly: CLSCompliant( true )] 50 | #if !NCRUNCH 51 | [assembly: AllowPartiallyTrustedCallers] 52 | #endif 53 | 54 | [assembly: InternalsVisibleTo( "CsvHelper.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001000db97564beef98ad18a76ba31f769fab92b14341c9c37ed12f8004bb2a1a7fe42ad829b0e285915a816f05a32325c5e0ba83bd69d8f4d26a0785ccf446749842ad038f7325601a99c59a323dfa7ecf210139159da0aad1822b5d9c9be6d914ecbaa8b8c908c4af798a89b8777010971d81975079a49662ced398c742ff186a94" )] 55 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/CsvWriterReferenceMappingPrefixTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2014 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is licensed under the MS-PL 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html 4 | // http://csvhelper.com 5 | using System; 6 | using System.Collections.Generic; 7 | using System.IO; 8 | using System.Text; 9 | using CsvHelper.Configuration; 10 | using Microsoft.VisualStudio.TestTools.UnitTesting; 11 | 12 | namespace CsvHelper.Tests 13 | { 14 | [TestClass] 15 | public class CsvWriterReferenceMappingPrefixTests 16 | { 17 | [TestMethod] 18 | public void ReferencesWithPrefixTest() 19 | { 20 | using( var stream = new MemoryStream() ) 21 | using( var reader = new StreamReader( stream ) ) 22 | using( var writer = new StreamWriter( stream ) ) 23 | using( var csv = new CsvWriter( writer ) ) 24 | { 25 | csv.Configuration.RegisterClassMap(); 26 | 27 | var list = new List(); 28 | for( var i = 0; i < 4; i++ ) 29 | { 30 | var row = i + 1; 31 | list.Add( new A 32 | { 33 | Id = "a" + row, 34 | B = new B 35 | { 36 | Id = "b" + row, 37 | C = new C 38 | { 39 | Id = "c" + row 40 | } 41 | } 42 | } ); 43 | } 44 | 45 | csv.WriteRecords( list ); 46 | writer.Flush(); 47 | stream.Position = 0; 48 | 49 | var data = reader.ReadToEnd(); 50 | 51 | var expected = new StringBuilder(); 52 | expected.AppendLine( "Id,BPrefix_Id,C.CId" ); 53 | expected.AppendLine( "a1,b1,c1" ); 54 | expected.AppendLine( "a2,b2,c2" ); 55 | expected.AppendLine( "a3,b3,c3" ); 56 | expected.AppendLine( "a4,b4,c4" ); 57 | Assert.AreEqual( expected.ToString(), data ); 58 | } 59 | } 60 | 61 | private class A 62 | { 63 | public string Id { get; set; } 64 | 65 | public B B { get; set; } 66 | } 67 | 68 | private class B 69 | { 70 | public string Id { get; set; } 71 | 72 | public C C { get; set; } 73 | } 74 | 75 | private class C 76 | { 77 | public string Id { get; set; } 78 | } 79 | 80 | private sealed class AMap : CsvClassMap 81 | { 82 | public AMap() 83 | { 84 | Map( m => m.Id ); 85 | References( m => m.B ).Prefix( "BPrefix_" ); 86 | } 87 | } 88 | 89 | private sealed class BMap : CsvClassMap 90 | { 91 | public BMap() 92 | { 93 | Map( m => m.Id ); 94 | References( m => m.C ).Prefix(); 95 | } 96 | } 97 | 98 | private sealed class CMap : CsvClassMap 99 | { 100 | public CMap() 101 | { 102 | Map( m => m.Id ).Name( "CId" ); 103 | } 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/.nuget/NuGet.targets: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(MSBuildProjectDirectory)\..\ 5 | $([System.IO.Path]::Combine($(SolutionDir), ".nuget")) 6 | $(NuGetToolsPath)\nuget.exe 7 | $([System.IO.Path]::Combine($(ProjectDir), "packages.config")) 8 | $([System.IO.Path]::Combine($(SolutionDir), "packages")) 9 | $(TargetDir.Trim('\\')) 10 | 11 | 12 | "" 13 | 14 | 15 | false 16 | 17 | 18 | false 19 | 20 | 21 | "$(NuGetExePath)" install "$(PackagesConfig)" -source $(PackageSources) -o "$(PackagesDir)" 22 | "$(NuGetExePath)" pack "$(ProjectPath)" -p Configuration=$(Configuration) -o "$(PackageOutputDir)" -symbols 23 | 24 | 25 | 26 | RestorePackages; 27 | $(BuildDependsOn); 28 | 29 | 30 | 31 | 32 | $(BuildDependsOn); 33 | BuildPackage; 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 46 | 47 | 48 | 49 | 51 | 52 | -------------------------------------------------------------------------------- /src/CsvHelper/ICsvFactory.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.IO; 6 | using CsvHelper.Configuration; 7 | 8 | namespace CsvHelper 9 | { 10 | /// 11 | /// Defines methods used to create 12 | /// CsvHelper classes. 13 | /// 14 | public interface ICsvFactory 15 | { 16 | /// 17 | /// Creates an . 18 | /// 19 | /// The text reader to use for the csv parser. 20 | /// The configuration to use for the csv parser. 21 | /// The created parser. 22 | ICsvParser CreateParser( TextReader reader, CsvConfiguration configuration ); 23 | 24 | /// 25 | /// Creates an . 26 | /// 27 | /// The text reader to use for the csv parser. 28 | /// The created parser. 29 | ICsvParser CreateParser( TextReader reader ); 30 | 31 | /// 32 | /// Creates an . 33 | /// 34 | /// The text reader to use for the csv reader. 35 | /// The configuration to use for the reader. 36 | /// The created reader. 37 | ICsvReader CreateReader( TextReader reader, CsvConfiguration configuration ); 38 | 39 | /// 40 | /// Creates an . 41 | /// 42 | /// The text reader to use for the csv reader. 43 | /// The created reader. 44 | ICsvReader CreateReader( TextReader reader ); 45 | 46 | /// 47 | /// Creates an . 48 | /// 49 | /// The parser used to create the reader. 50 | /// The created reader. 51 | ICsvReader CreateReader( ICsvParser parser ); 52 | 53 | /// 54 | /// Creates an . 55 | /// 56 | /// The text writer to use for the csv writer. 57 | /// The configuration to use for the writer. 58 | /// The created writer. 59 | ICsvWriter CreateWriter( TextWriter writer, CsvConfiguration configuration ); 60 | 61 | /// 62 | /// Creates an . 63 | /// 64 | /// The text writer to use for the csv writer. 65 | /// The created writer. 66 | ICsvWriter CreateWriter( TextWriter writer ); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/CsvHelper/ICsvWriter.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Collections; 7 | using CsvHelper.Configuration; 8 | using CsvHelper.TypeConversion; 9 | 10 | namespace CsvHelper 11 | { 12 | /// 13 | /// Defines methods used to write to a CSV file. 14 | /// 15 | public interface ICsvWriter : ICsvWriterRow, IDisposable 16 | { 17 | /// 18 | /// Gets the serializer. 19 | /// 20 | ICsvSerializer Serializer { get; } 21 | 22 | /// 23 | /// Ends writing of the current record and starts a new record. 24 | /// This needs to be called to serialize the row to the writer. 25 | /// 26 | void NextRecord(); 27 | 28 | /// 29 | /// Writes the list of records to the CSV file. 30 | /// 31 | /// The list of records to write. 32 | void WriteRecords( IEnumerable records ); 33 | 34 | /// 35 | /// Clears the record cache for the given type. After is called the 36 | /// first time, code is dynamically generated based on the , 37 | /// compiled, and stored for the given type T. If the 38 | /// changes, needs to be called to update the 39 | /// record cache. 40 | /// 41 | /// The record type. 42 | void ClearRecordCache(); 43 | 44 | /// 45 | /// Clears the record cache for the given type. After is called the 46 | /// first time, code is dynamically generated based on the , 47 | /// compiled, and stored for the given type T. If the 48 | /// changes, needs to be called to update the 49 | /// record cache. 50 | /// 51 | /// The record type. 52 | void ClearRecordCache( Type type ); 53 | 54 | /// 55 | /// Clears the record cache for all types. After is called the 56 | /// first time, code is dynamically generated based on the , 57 | /// compiled, and stored for the given type T. If the 58 | /// changes, needs to be called to update the 59 | /// record cache. 60 | /// 61 | void ClearRecordCache(); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/CsvHelper/Configuration/AutoMapOptions.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using CsvHelper.TypeConversion; 3 | 4 | namespace CsvHelper.Configuration 5 | { 6 | /// 7 | /// Options used when auto mapping. 8 | /// 9 | public class AutoMapOptions 10 | { 11 | /// 12 | /// Gets or sets a value indicating whether references 13 | /// should be ignored when auto mapping. True to ignore 14 | /// references, otherwise false. Default is false. 15 | /// 16 | public bool IgnoreReferences { get; set; } 17 | 18 | /// 19 | /// Gets or sets a value indicating if headers of reference 20 | /// properties/fields should get prefixed by the parent property/field 21 | /// name when automapping. 22 | /// True to prefix, otherwise false. Default is false. 23 | /// 24 | public bool PrefixReferenceHeaders { get; set; } 25 | 26 | /// 27 | /// Gets or sets a value indicating if private 28 | /// properties/fields should be read from and written to. 29 | /// True to include private properties/fields, otherwise false. Default is false. 30 | /// 31 | public bool IncludePrivateProperties { get; set; } 32 | 33 | /// 34 | /// Gets or sets the member types that are used when auto mapping. 35 | /// MemberTypes are flags, so you can choose more than one. 36 | /// Default is Properties. 37 | /// 38 | public MemberTypes MemberTypes { get; set; } = MemberTypes.Properties; 39 | 40 | /// 41 | /// Gets or sets the . 42 | /// 43 | public TypeConverterOptionsFactory TypeConverterOptionsFactory { get; set; } = new TypeConverterOptionsFactory(); 44 | 45 | /// 46 | /// Create options using the defaults. 47 | /// 48 | public AutoMapOptions() { } 49 | 50 | /// 51 | /// Creates options using the given . 52 | /// 53 | /// 54 | public AutoMapOptions( CsvConfiguration configuration ) 55 | { 56 | IgnoreReferences = configuration.IgnoreReferences; 57 | PrefixReferenceHeaders = configuration.PrefixReferenceHeaders; 58 | IncludePrivateProperties = configuration.IncludePrivateMembers; 59 | MemberTypes = configuration.MemberTypes; 60 | TypeConverterOptionsFactory = configuration.TypeConverterOptionsFactory; 61 | } 62 | 63 | /// 64 | /// Creates a copy of the auto map options. 65 | /// 66 | /// A copy of the auto map options. 67 | public AutoMapOptions Copy() 68 | { 69 | var copy = new AutoMapOptions(); 70 | var properties = GetType().GetProperties( BindingFlags.Public | BindingFlags.Instance ); 71 | foreach( var property in properties ) 72 | { 73 | property.SetValue( copy, property.GetValue( this, null ), null ); 74 | } 75 | 76 | return copy; 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Reading/MultipleHeadersTests.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using CsvHelper.Configuration; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | 5 | namespace CsvHelper.Tests.Reading 6 | { 7 | [TestClass] 8 | public class MultipleHeadersTests 9 | { 10 | [TestMethod] 11 | public void ReadWithoutMapTest() 12 | { 13 | using( var stream = new MemoryStream() ) 14 | using( var reader = new StreamReader( stream ) ) 15 | using( var writer = new StreamWriter( stream ) ) 16 | using( var csv = new CsvReader( reader ) ) 17 | { 18 | writer.WriteLine( "A,B" ); 19 | writer.WriteLine( "1,one" ); 20 | writer.WriteLine( "Y,Z" ); 21 | writer.WriteLine( "two,2" ); 22 | writer.Flush(); 23 | stream.Position = 0; 24 | 25 | csv.Read(); 26 | csv.ReadHeader(); 27 | csv.Read(); 28 | 29 | Assert.AreEqual( 1, csv.GetField( "A" ) ); 30 | Assert.AreEqual( "one", csv.GetField( "B" ) ); 31 | 32 | csv.Read(); 33 | csv.ReadHeader(); 34 | csv.Read(); 35 | 36 | Assert.AreEqual( "two", csv.GetField( "Y" ) ); 37 | Assert.AreEqual( 2, csv.GetField( "Z" ) ); 38 | } 39 | } 40 | 41 | [TestMethod] 42 | public void ReadWithMapTest() 43 | { 44 | using( var stream = new MemoryStream() ) 45 | using( var reader = new StreamReader( stream ) ) 46 | using( var writer = new StreamWriter( stream ) ) 47 | using( var csv = new CsvReader( reader ) ) 48 | { 49 | writer.WriteLine( "A,B" ); 50 | writer.WriteLine( "1,one" ); 51 | writer.WriteLine( "Y,Z" ); 52 | writer.WriteLine( "two,2" ); 53 | writer.Flush(); 54 | stream.Position = 0; 55 | 56 | csv.Configuration.RegisterClassMap(); 57 | csv.Configuration.RegisterClassMap(); 58 | 59 | csv.Read(); 60 | csv.ReadHeader(); 61 | 62 | csv.Read(); 63 | var alphaRecord = csv.GetRecord(); 64 | 65 | Assert.AreEqual( 1, alphaRecord.A ); 66 | Assert.AreEqual( "one", alphaRecord.B ); 67 | 68 | csv.Read(); 69 | csv.ReadHeader(); 70 | 71 | csv.Read(); 72 | var omegaRecord = csv.GetRecord(); 73 | 74 | Assert.AreEqual( "two", omegaRecord.Y ); 75 | Assert.AreEqual( 2, omegaRecord.Z ); 76 | } 77 | } 78 | 79 | private class Alpha 80 | { 81 | public int A { get; set; } 82 | public string B { get; set; } 83 | } 84 | 85 | private class Omega 86 | { 87 | public string Y { get; set; } 88 | public int Z { get; set; } 89 | } 90 | 91 | private sealed class AlphaMap : CsvClassMap 92 | { 93 | public AlphaMap() 94 | { 95 | Map( m => m.A ); 96 | Map( m => m.B ); 97 | } 98 | } 99 | 100 | private sealed class OmegaMap : CsvClassMap 101 | { 102 | public OmegaMap() 103 | { 104 | Map( m => m.Y ); 105 | Map( m => m.Z ); 106 | } 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/TypeConversion/EnumConverterTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Globalization; 7 | using System.IO; 8 | using System.Text; 9 | using CsvHelper.Configuration; 10 | using Microsoft.VisualStudio.TestTools.UnitTesting; 11 | using CsvHelper.TypeConversion; 12 | 13 | namespace CsvHelper.Tests.TypeConversion 14 | { 15 | [TestClass] 16 | public class EnumConverterTests 17 | { 18 | [TestMethod] 19 | public void ConstructorTest() 20 | { 21 | try 22 | { 23 | new EnumConverter( typeof( string ) ); 24 | Assert.Fail(); 25 | } 26 | catch( ArgumentException ex ) 27 | { 28 | Assert.AreEqual( "'System.String' is not an Enum.", ex.Message ); 29 | } 30 | } 31 | 32 | [TestMethod] 33 | public void ConvertToStringTest() 34 | { 35 | var converter = new EnumConverter( typeof( TestEnum ) ); 36 | var propertyMapData = new CsvPropertyMapData( null ) 37 | { 38 | TypeConverter = converter, 39 | TypeConverterOptions = { CultureInfo = CultureInfo.CurrentCulture } 40 | }; 41 | 42 | Assert.AreEqual( "None", converter.ConvertToString( (TestEnum)0, null, propertyMapData ) ); 43 | Assert.AreEqual( "None", converter.ConvertToString( TestEnum.None, null, propertyMapData ) ); 44 | Assert.AreEqual( "One", converter.ConvertToString( (TestEnum)1, null, propertyMapData ) ); 45 | Assert.AreEqual( "One", converter.ConvertToString( TestEnum.One, null, propertyMapData ) ); 46 | Assert.AreEqual( "", converter.ConvertToString( null, null, propertyMapData ) ); 47 | } 48 | 49 | [TestMethod] 50 | public void ConvertFromStringTest() 51 | { 52 | var converter = new EnumConverter( typeof( TestEnum ) ); 53 | 54 | var propertyMapData = new CsvPropertyMapData( null ); 55 | propertyMapData.TypeConverterOptions.CultureInfo = CultureInfo.CurrentCulture; 56 | 57 | Assert.AreEqual( TestEnum.One, converter.ConvertFromString( "One", null, propertyMapData ) ); 58 | Assert.AreEqual( TestEnum.One, converter.ConvertFromString( "one", null, propertyMapData ) ); 59 | Assert.AreEqual( TestEnum.One, converter.ConvertFromString( "1", null, propertyMapData ) ); 60 | try 61 | { 62 | Assert.AreEqual( TestEnum.One, converter.ConvertFromString( "", null, propertyMapData ) ); 63 | Assert.Fail(); 64 | } 65 | catch( CsvTypeConverterException ) 66 | { 67 | } 68 | 69 | try 70 | { 71 | Assert.AreEqual( TestEnum.One, converter.ConvertFromString( null, null, propertyMapData ) ); 72 | Assert.Fail(); 73 | } 74 | catch( CsvTypeConverterException ) 75 | { 76 | } 77 | } 78 | 79 | private enum TestEnum 80 | { 81 | None = 0, 82 | One = 1, 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/Defaults/WritingDefaultsTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using CsvHelper.Configuration; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | 9 | namespace CsvHelper.Tests.Defaults 10 | { 11 | [TestClass] 12 | public class WritingDefaultsTests 13 | { 14 | [TestMethod] 15 | public void EmptyFieldsOnNullReferencePropertyTest() 16 | { 17 | using( var stream = new MemoryStream() ) 18 | using( var reader = new StreamReader( stream ) ) 19 | using( var writer = new StreamWriter( stream ) ) 20 | using( var csv = new CsvWriter( writer ) ) 21 | { 22 | var records = new List 23 | { 24 | new A 25 | { 26 | AId = 1, 27 | }, 28 | new A 29 | { 30 | AId = 2, 31 | B = new B 32 | { 33 | BId = 3, 34 | }, 35 | }, 36 | }; 37 | 38 | csv.Configuration.UseNewObjectForNullReferenceMembers = false; 39 | csv.Configuration.RegisterClassMap(); 40 | csv.WriteRecords( records ); 41 | 42 | writer.Flush(); 43 | stream.Position = 0; 44 | 45 | var data = reader.ReadToEnd(); 46 | var expected = "AId,BId,CId\r\n" + 47 | "1,,\r\n" + 48 | "2,3,0\r\n"; 49 | Assert.AreEqual( expected, data ); 50 | } 51 | } 52 | 53 | [TestMethod] 54 | public void DefaultFieldsOnNullReferencePropertyTest() 55 | { 56 | using( var stream = new MemoryStream() ) 57 | using( var reader = new StreamReader( stream ) ) 58 | using( var writer = new StreamWriter( stream ) ) 59 | using( var csv = new CsvWriter( writer ) ) 60 | { 61 | var records = new List 62 | { 63 | new A 64 | { 65 | AId = 1, 66 | }, 67 | new A 68 | { 69 | AId = 2, 70 | B = new B 71 | { 72 | BId = 3, 73 | }, 74 | }, 75 | }; 76 | 77 | csv.Configuration.RegisterClassMap(); 78 | csv.WriteRecords( records ); 79 | 80 | writer.Flush(); 81 | stream.Position = 0; 82 | 83 | var data = reader.ReadToEnd(); 84 | var expected = "AId,BId,CId\r\n" + 85 | "1,0,0\r\n" + 86 | "2,3,0\r\n"; 87 | Assert.AreEqual( expected, data ); 88 | } 89 | } 90 | 91 | private class A 92 | { 93 | public int AId { get; set; } 94 | 95 | public B B { get; set; } 96 | } 97 | 98 | private sealed class AMap : CsvClassMap 99 | { 100 | public AMap() 101 | { 102 | Map( m => m.AId ).Default( 1 ); 103 | References( m => m.B ); 104 | } 105 | } 106 | 107 | public class B 108 | { 109 | public int BId { get; set; } 110 | public int CId { get; set; } 111 | } 112 | 113 | public sealed class BMap : CsvClassMap 114 | { 115 | public BMap() 116 | { 117 | AutoMap(); 118 | } 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/ClassMapOrderingTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Collections.Generic; 7 | using System.IO; 8 | using System.Linq; 9 | using System.Text; 10 | using CsvHelper.Configuration; 11 | using Microsoft.VisualStudio.TestTools.UnitTesting; 12 | 13 | namespace CsvHelper.Tests 14 | { 15 | [TestClass] 16 | public class ClassMapOrderingTests 17 | { 18 | [TestMethod] 19 | public void OrderingTest() 20 | { 21 | var list = new List 22 | { 23 | new ContainerClass 24 | { 25 | Contents = new ThirdClass 26 | { 27 | Third = 3, 28 | Second = new SecondClass 29 | { 30 | Second = 2, 31 | }, 32 | First = new FirstClass 33 | { 34 | First = 1, 35 | }, 36 | } 37 | }, 38 | }; 39 | 40 | using( var stream = new MemoryStream() ) 41 | using( var reader = new StreamReader( stream ) ) 42 | using( var writer = new StreamWriter( stream ) ) 43 | using( var csv = new CsvWriter( writer ) ) 44 | { 45 | csv.Configuration.RegisterClassMap(); 46 | csv.WriteRecords( list ); 47 | writer.Flush(); 48 | stream.Position = 0; 49 | 50 | Assert.AreEqual( "First,Second,Third", reader.ReadLine() ); 51 | } 52 | } 53 | 54 | private class ContainerClass 55 | { 56 | public ThirdClass Contents { get; set; } 57 | } 58 | 59 | private class ThirdClass 60 | { 61 | public int Third { get; set; } 62 | 63 | public SecondClass Second { get; set; } 64 | 65 | public FirstClass First { get; set; } 66 | } 67 | 68 | private sealed class ContainerClassMap : CsvClassMap 69 | { 70 | public ContainerClassMap() 71 | { 72 | References( m => m.Contents ); 73 | } 74 | } 75 | 76 | private sealed class ThirdClassMap : CsvClassMap 77 | { 78 | public ThirdClassMap() 79 | { 80 | References( m => m.First ); 81 | References( m => m.Second ); 82 | Map( m => m.Third ); 83 | } 84 | } 85 | 86 | private class SecondClass 87 | { 88 | public int Second { get; set; } 89 | } 90 | 91 | private sealed class SecondClassMap : CsvClassMap 92 | { 93 | public SecondClassMap() 94 | { 95 | Map( m => m.Second ); 96 | } 97 | } 98 | 99 | private class FirstClass 100 | { 101 | public int First { get; set; } 102 | } 103 | 104 | private sealed class FirstClassMap : CsvClassMap 105 | { 106 | public FirstClassMap() 107 | { 108 | Map( m => m.First ); 109 | } 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/LocalCultureTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Globalization; 8 | using System.IO; 9 | using System.Linq; 10 | using System.Threading; 11 | using CsvHelper.Configuration; 12 | using Microsoft.VisualStudio.TestTools.UnitTesting; 13 | 14 | namespace CsvHelper.Tests 15 | { 16 | [TestClass] 17 | public class LocalCultureTests 18 | { 19 | // In 'uk-UA' decimal separator is the ',' 20 | // For 'Invariant' and many other cultures decimal separator is '.' 21 | 22 | [TestMethod] 23 | public void ReadRecordsTest() 24 | { 25 | RunTestInSpecificCulture( ReadRecordsTestBody, "uk-UA" ); 26 | } 27 | 28 | [TestMethod] 29 | public void WriteRecordsTest() 30 | { 31 | RunTestInSpecificCulture( WriteRecordsTestBody, "uk-UA" ); 32 | } 33 | 34 | private static void RunTestInSpecificCulture( Action action, string cultureName ) 35 | { 36 | var originalCulture = CultureInfo.CurrentCulture; 37 | try 38 | { 39 | CultureInfo.CurrentCulture = new CultureInfo( cultureName ); 40 | action(); 41 | } 42 | finally 43 | { 44 | CultureInfo.CurrentCulture = originalCulture; 45 | } 46 | } 47 | 48 | private static void ReadRecordsTestBody() 49 | { 50 | const string source = "DateTimeColumn;DecimalColumn\r\n" + 51 | "11.11.2010;12,0\r\n"; 52 | 53 | var configuration = new CsvConfiguration 54 | { 55 | Delimiter = ";", 56 | }; 57 | var reader = new CsvReader( new CsvParser( new StringReader( source ), configuration ) ); 58 | 59 | var records = reader.GetRecords().ToList(); 60 | 61 | Assert.AreEqual( 1, records.Count() ); 62 | var record = records.First(); 63 | Assert.AreEqual( 12.0m, record.DecimalColumn ); 64 | Assert.AreEqual( new DateTime( 2010, 11, 11 ), record.DateTimeColumn ); 65 | } 66 | 67 | private static void WriteRecordsTestBody() 68 | { 69 | var records = new List 70 | { 71 | new TestRecordWithDecimal 72 | { 73 | DecimalColumn = 12.0m, 74 | DateTimeColumn = new DateTime( 2010, 11, 11 ) 75 | } 76 | }; 77 | 78 | var writer = new StringWriter(); 79 | var csv = new CsvWriter( writer, new CsvConfiguration { Delimiter = ";" } ); 80 | 81 | csv.WriteRecords( records ); 82 | 83 | var csvFile = writer.ToString(); 84 | 85 | const string expected = "DecimalColumn;DateTimeColumn\r\n" + 86 | "12,0;11.11.2010 0:00:00\r\n"; 87 | 88 | Assert.AreEqual( expected, csvFile ); 89 | } 90 | 91 | private class TestRecordWithDecimal 92 | { 93 | public decimal DecimalColumn { get; set; } 94 | public DateTime DateTimeColumn { get; set; } 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/CsvReaderReferenceMappingTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.IO; 6 | using System.Linq; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | using CsvHelper.Configuration; 9 | 10 | namespace CsvHelper.Tests 11 | { 12 | [TestClass] 13 | public class CsvReaderReferenceMappingTests 14 | { 15 | [TestMethod] 16 | public void NestedReferencesClassMappingTest() 17 | { 18 | using( var stream = new MemoryStream() ) 19 | using( var reader = new StreamReader( stream ) ) 20 | using( var writer = new StreamWriter( stream ) ) 21 | using( var csv = new CsvReader( reader ) ) 22 | { 23 | csv.Configuration.RegisterClassMap(); 24 | 25 | writer.WriteLine( "AId,BId,CId,DId" ); 26 | writer.WriteLine( "a1,b1,c1,d1" ); 27 | writer.WriteLine( "a2,b2,c2,d2" ); 28 | writer.WriteLine( "a3,b3,c3,d3" ); 29 | writer.WriteLine( "a4,b4,c4,d4" ); 30 | writer.Flush(); 31 | stream.Position = 0; 32 | 33 | var list = csv.GetRecords().ToList(); 34 | 35 | Assert.IsNotNull( list ); 36 | Assert.AreEqual( 4, list.Count ); 37 | 38 | for( var i = 0; i < 4; i++ ) 39 | { 40 | var rowId = i + 1; 41 | var row = list[i]; 42 | Assert.AreEqual( "a" + rowId, row.Id ); 43 | Assert.AreEqual( "b" + rowId, row.B.Id ); 44 | Assert.AreEqual( "c" + rowId, row.B.C.Id ); 45 | Assert.AreEqual( "d" + rowId, row.B.C.D.Id ); 46 | } 47 | } 48 | } 49 | 50 | private class A 51 | { 52 | public string Id { get; set; } 53 | 54 | public B B { get; set; } 55 | } 56 | 57 | private class B 58 | { 59 | public string Id { get; set; } 60 | 61 | public C C { get; set; } 62 | } 63 | 64 | private class C 65 | { 66 | public string Id { get; set; } 67 | 68 | public D D { get; set; } 69 | } 70 | 71 | private class D 72 | { 73 | public string Id { get; set; } 74 | } 75 | 76 | private sealed class AMap : CsvClassMap 77 | { 78 | public AMap() 79 | { 80 | Map( m => m.Id ).Name( "AId" ); 81 | References( m => m.B ); 82 | } 83 | } 84 | 85 | private sealed class BMap : CsvClassMap 86 | { 87 | public BMap() 88 | { 89 | Map( m => m.Id ).Name( "BId" ); 90 | References( m => m.C ); 91 | } 92 | } 93 | 94 | private sealed class CMap : CsvClassMap 95 | { 96 | public CMap() 97 | { 98 | Map( m => m.Id ).Name( "CId" ); 99 | References( m => m.D ); 100 | } 101 | } 102 | 103 | private sealed class DMap : CsvClassMap 104 | { 105 | public DMap() 106 | { 107 | Map( m => m.Id ).Name( "DId" ); 108 | } 109 | } 110 | 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/CsvHelper/Configuration/CsvPropertyNameCollection.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System.Collections; 6 | using System.Collections.Generic; 7 | 8 | namespace CsvHelper.Configuration 9 | { 10 | /// 11 | /// A collection that holds property/field names. 12 | /// 13 | public class CsvPropertyNameCollection : IEnumerable 14 | { 15 | private readonly List names = new List(); 16 | 17 | /// 18 | /// Gets the name at the given index. If a prefix is set, 19 | /// it will be prepended to the name. 20 | /// 21 | /// 22 | /// 23 | public string this[int index] 24 | { 25 | get { return Prefix + names[index]; } 26 | set { names[index] = value; } 27 | } 28 | 29 | /// 30 | /// Gets the prefix to use for each name. 31 | /// 32 | public string Prefix { get; set; } 33 | 34 | /// 35 | /// Gets the raw list of names without 36 | /// the prefix being prepended. 37 | /// 38 | public List Names => names; 39 | 40 | /// 41 | /// Gets the count. 42 | /// 43 | public int Count => names.Count; 44 | 45 | /// 46 | /// Adds the given name to the collection. 47 | /// 48 | /// The name to add. 49 | public void Add( string name ) 50 | { 51 | names.Add( name ); 52 | } 53 | 54 | /// 55 | /// Clears all names from the collection. 56 | /// 57 | public void Clear() 58 | { 59 | names.Clear(); 60 | } 61 | 62 | /// 63 | /// Adds a range of names to the collection. 64 | /// 65 | /// The range to add. 66 | public void AddRange( IEnumerable names ) 67 | { 68 | this.names.AddRange( names ); 69 | } 70 | 71 | /// 72 | /// Returns an enumerator that iterates through the collection. 73 | /// 74 | /// 75 | /// A that can be used to iterate through the collection. 76 | /// 77 | /// 1 78 | public IEnumerator GetEnumerator() 79 | { 80 | for( var i = 0; i < names.Count; i++ ) 81 | { 82 | yield return this[i]; 83 | } 84 | } 85 | 86 | /// 87 | /// Returns an enumerator that iterates through a collection. 88 | /// 89 | /// 90 | /// An object that can be used to iterate through the collection. 91 | /// 92 | /// 2 93 | IEnumerator IEnumerable.GetEnumerator() 94 | { 95 | return names.GetEnumerator(); 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/CsvReaderConstructorTests.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2009-2015 Josh Close and Contributors 2 | // This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0. 3 | // See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0. 4 | // http://csvhelper.com 5 | using System; 6 | using System.IO; 7 | using CsvHelper.Configuration; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | namespace CsvHelper.Tests 11 | { 12 | [TestClass] 13 | public class CsvReaderConstructorTests 14 | { 15 | [TestMethod] 16 | public void InvalidParameterTest() 17 | { 18 | try 19 | { 20 | new CsvReader( new TestParser() ); 21 | Assert.Fail(); 22 | } 23 | catch( CsvConfigurationException ) 24 | { 25 | } 26 | } 27 | 28 | [TestMethod] 29 | public void EnsureInternalsAreSetupCorrectlyWhenPassingTextReaderTest() 30 | { 31 | using( var stream = new MemoryStream() ) 32 | using( var reader = new StreamReader( stream ) ) 33 | using( var csv = new CsvReader( reader ) ) 34 | { 35 | Assert.AreSame( csv.Configuration, csv.Parser.Configuration ); 36 | } 37 | } 38 | 39 | [TestMethod] 40 | public void EnsureInternalsAreSetupCorrectlyWhenPassingTextReaderAndConfigurationTest() 41 | { 42 | using( var stream = new MemoryStream() ) 43 | using( var reader = new StreamReader( stream ) ) 44 | using( var csv = new CsvReader( reader, new CsvConfiguration() ) ) 45 | { 46 | Assert.AreSame( csv.Configuration, csv.Parser.Configuration ); 47 | } 48 | } 49 | 50 | [TestMethod] 51 | public void EnsureInternalsAreSetupCorrectlyWhenPassingParserTest() 52 | { 53 | using( var stream = new MemoryStream() ) 54 | using( var reader = new StreamReader( stream ) ) 55 | { 56 | var parser = new CsvParser( reader ); 57 | 58 | using( var csv = new CsvReader( parser ) ) 59 | { 60 | Assert.AreSame( csv.Configuration, csv.Parser.Configuration ); 61 | Assert.AreSame( parser, csv.Parser ); 62 | } 63 | } 64 | } 65 | 66 | private class TestParser : ICsvParser 67 | { 68 | public void Dispose() 69 | { 70 | throw new NotImplementedException(); 71 | } 72 | 73 | public TextReader TextReader { get; } 74 | 75 | public ICsvParserConfiguration Configuration { get; private set; } 76 | 77 | public int FieldCount 78 | { 79 | get { throw new NotImplementedException(); } 80 | } 81 | 82 | public int RawRow { get; private set; } 83 | 84 | public string RawRecord { get; private set; } 85 | 86 | public string[] Read() 87 | { 88 | throw new NotImplementedException(); 89 | } 90 | 91 | public long CharPosition 92 | { 93 | get { throw new NotImplementedException(); } 94 | } 95 | 96 | public long BytePosition { get; private set; } 97 | 98 | public int Row 99 | { 100 | get { throw new NotImplementedException(); } 101 | } 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/CsvHelper.Tests/TypeConversion/TypeConverterOptionsTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using CsvHelper.Configuration; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | namespace CsvHelper.Tests.TypeConversion 11 | { 12 | [TestClass] 13 | public class TypeConverterOptionsTests 14 | { 15 | [TestMethod] 16 | public void GlobalNullValueTest() 17 | { 18 | using( var stream = new MemoryStream() ) 19 | using( var writer = new StreamWriter( stream ) ) 20 | using( var reader = new StreamReader( stream ) ) 21 | using( var csv = new CsvReader( reader ) ) 22 | { 23 | writer.WriteLine( "," ); 24 | writer.Flush(); 25 | stream.Position = 0; 26 | 27 | csv.Configuration.HasHeaderRecord = false; 28 | csv.Configuration.TypeConverterOptionsFactory.GetOptions().NullValues.Add( string.Empty ); 29 | var records = csv.GetRecords().ToList(); 30 | 31 | Assert.IsNull( records[0].Id ); 32 | Assert.IsNull( records[0].Name ); 33 | } 34 | } 35 | 36 | [TestMethod] 37 | public void MappingNullValueTest() 38 | { 39 | using( var stream = new MemoryStream() ) 40 | using( var writer = new StreamWriter( stream ) ) 41 | using( var reader = new StreamReader( stream ) ) 42 | using( var csv = new CsvReader( reader ) ) 43 | { 44 | writer.WriteLine( "," ); 45 | writer.Flush(); 46 | stream.Position = 0; 47 | 48 | csv.Configuration.HasHeaderRecord = false; 49 | csv.Configuration.RegisterClassMap(); 50 | var records = csv.GetRecords().ToList(); 51 | 52 | Assert.IsNull( records[0].Id ); 53 | Assert.IsNull( records[0].Name ); 54 | } 55 | } 56 | 57 | [TestMethod] 58 | public void GlobalAndMappingNullValueTest() 59 | { 60 | using( var stream = new MemoryStream() ) 61 | using( var writer = new StreamWriter( stream ) ) 62 | using( var reader = new StreamReader( stream ) ) 63 | using( var csv = new CsvReader( reader ) ) 64 | { 65 | writer.WriteLine( "," ); 66 | writer.Flush(); 67 | stream.Position = 0; 68 | 69 | csv.Configuration.HasHeaderRecord = false; 70 | csv.Configuration.TypeConverterOptionsFactory.GetOptions().NullValues.Add( "null" ); 71 | csv.Configuration.RegisterClassMap(); 72 | var records = csv.GetRecords().ToList(); 73 | 74 | Assert.IsNull( records[0].Id ); 75 | Assert.IsNull( records[0].Name ); 76 | } 77 | } 78 | 79 | private class Test 80 | { 81 | public int? Id { get; set; } 82 | public string Name { get; set; } 83 | } 84 | 85 | private sealed class TestMap : CsvClassMap 86 | { 87 | public TestMap() 88 | { 89 | Map( m => m.Id ); 90 | Map( m => m.Name ).TypeConverterOption.NullValues( string.Empty ); 91 | } 92 | } 93 | 94 | // auto map options have defaults 95 | // map options could be default or custom if set 96 | // global has defaults or custom 97 | // merge global with map 98 | } 99 | } 100 | --------------------------------------------------------------------------------