1

I wrote this script from some resources I found. It's working but I some files I have problem. I am new in F# so how can I change line with FileHelpersException to get exact line where is the problem? Thanks

// Learn more about F# at http://fsharp.net
// See the 'F# Tutorial' project for more help.
open FileHelpers  
open System

[<DelimitedRecord(",")>]
type CsvRecord =
    class
        val field1 : string
        val field2 : string
        val field3 : int
        new () = {
        field1 = ""
        field2 = ""
        field3 = 0
        }
    end

[<EntryPoint>]
let main argv = 
    use file = System.IO.File.CreateText("result.txt")
    let engine = new FileHelperEngine<CsvRecord>()
    engine.Encoding <- new Text.UTF8Encoding()
    let res = 
       try
          engine.ReadFile("test.csv")
       with
          | :? FileHelpersException -> Array.empty<CsvRecord>
    for record in res do
         fprintfn file "%s" record.field1
    printf "DONE!"
    let s = Console.ReadLine()
    0 // return an integer exit code
4

2 回答 2

5

我建议您改用CsvTypeProvider。当存在不匹配时,错误消息会指出有错误的行

open FSharp.Data

[<EntryPoint>]
let main argv = 
    use file = System.IO.File.CreateText("result.txt")
    let csv = new CsvProvider<"test.csv">()
    for record in csv.Data do
        fprintfn file "%s" record.field1

如果您想忽略有错误的行,只需将IgnoreErrors=true其作为额外参数传递给 CsvProvider

于 2013-08-06T13:31:07.590 回答
2

这个问题是关于您正在使用的 FileHelpers 库,而不是 F#,因此查看文档可能会有所帮助。在这种情况下,您可以检查ConvertException而不是FileHelpersException,其中包含为您提供有关该成员的更多详细信息的成员。

try
    engine.ReadFile("test.csv")
with
    | :? ConvertException as ex ->
        printfn "ERROR: Line %d Col %d" ex.LineNumber ex.ColumnNumber
        Array.empty<CsvRecord>

不过,我同意 Gustavo,您可能会发现使用 CsvTypeProvider 更容易。

于 2013-08-06T14:51:30.357 回答