Skip to content

CSV

csv Parameter Settings

```csharp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System;
using System.Collections.Generic;
using System.IO;
using HalconDotNet;

public static class HalconCameraConfig
{
    /// <summary>
    /// Set camera parameters from a 2-row CSV file (header + values)
    /// </summary>
    public static void ApplyCameraParamsFromCsv2Row(HTuple acqHandle, string csvFilePath)
    {
        if (!File.Exists(csvFilePath))
            throw new FileNotFoundException("CSV file not found", csvFilePath);

        var lines = File.ReadAllLines(csvFilePath);
        if (lines.Length < 2)
            throw new FormatException("CSV file must contain two rows: header and values");

        var headers = lines[0].Split(',');
        var values = lines[1].Split(',');

        if (headers.Length != values.Length)
            throw new FormatException("The number of headers and values do not match");

        for (int i = 0; i < headers.Length; i++)
        {
            string key = headers[i].Trim();
            string valStr = values[i].Trim();

            if (string.IsNullOrEmpty(key))
                continue;

            HTuple val;
            if (double.TryParse(valStr, out double d))
                val = d;
            else if (int.TryParse(valStr, out int n))
                val = n;
            else
                val = valStr;

            try
            {
                HOperatorSet.SetFramegrabberParam(acqHandle, key, val);
                Console.WriteLine($"Set: {key} = {val}");
            }
            catch (HalconException ex)
            {
                Console.WriteLine($"Failed to set parameter: {key} = {val} → {ex.Message}");
            }
        }
    }

    /// <summary>
    /// Save parameters as 2-row CSV (header + values) from a dictionary
    /// </summary>
    public static void SaveCameraParamsToCsv2Row(string csvFilePath, Dictionary<string, string> paramDict)
    {
        if (paramDict == null || paramDict.Count == 0)
            throw new ArgumentException("Parameter dictionary is empty", nameof(paramDict));

        var headers = string.Join(",", paramDict.Keys);
        var values = string.Join(",", paramDict.Values);

        File.WriteAllLines(csvFilePath, new[] { headers, values });
    }
}