diff --git a/src/CsvHelper/Configuration/ConfigurationFunctions.cs b/src/CsvHelper/Configuration/ConfigurationFunctions.cs index 99ed29616..282f6b60b 100644 --- a/src/CsvHelper/Configuration/ConfigurationFunctions.cs +++ b/src/CsvHelper/Configuration/ConfigurationFunctions.cs @@ -209,7 +209,7 @@ public static string GetDelimiter(GetDelimiterArgs args) var match = Regex.Match(text, newLine); var line = match.Success ? text.Substring(0, match.Index) : text; - if (line.Length > 0) + if (line.Length > 0 && !(config.AllowComments && line[0] == config.Comment)) { var delimiterCounts = new Dictionary(); foreach (var delimiter in config.DetectDelimiterValues) diff --git a/tests/CsvHelper.Tests/Parsing/DetectDelimiterTests.cs b/tests/CsvHelper.Tests/Parsing/DetectDelimiterTests.cs index 91c51c4bb..bd40a3ef2 100644 --- a/tests/CsvHelper.Tests/Parsing/DetectDelimiterTests.cs +++ b/tests/CsvHelper.Tests/Parsing/DetectDelimiterTests.cs @@ -303,5 +303,21 @@ public void GetDelimiter_TextHasEmptyLines_DetectsDelimiter() var delimeter = ConfigurationFunctions.GetDelimiter(new Delegates.GetDelimiterArgs(s.ToString(), config)); Assert.Equal(";", delimeter); } + + [Fact] + public void GetDelimiter_TextHasComments_DetectsDelimiter() + { + var s = new StringBuilder(); + s.AppendLine("#comment,,,"); + s.AppendLine("Id;Name"); + s.AppendLine("1;2"); + var config = new CsvConfiguration(CultureInfo.InvariantCulture) + { + AllowComments = true, + Comment = '#', + DetectDelimiter = true, + }; + Assert.Equal(";", ConfigurationFunctions.GetDelimiter(new Delegates.GetDelimiterArgs(s.ToString(), config))); + } } }