Generate C # model class from csv file structure

The goal is that after entering the csv file, the magic tool outputs a C # class with csv fields. Consider an example.

Enter myFile.csv:

Year,Make,Model
1997,Ford,E350
2000,Mercury,Cougar

The output of myFile.cs

public class myFile
{
   public string Year;
   public string Make;
   public string Model;
}

So, the only thing I will need to fix is ​​the property types. After that I will use this class with FileHelpers to read the csv file. Later it will be mapped to the EntityFramework class (using AutoMapper) and saved to the database.

Actually, https://csv2entity.codeplex.com/ looks like what I need, but it just doesn’t work - I installed it and nothing has changed in my Visual Studio, a new template has not appeared. The project is completely dead. Open source and ... decided maybe I am just asking this question in stackoverflow :)

FileHelpers , . 50 , , , .

, , ?

+5
4

, , :

  • , . " β„–" "OrderNo".
  • . [DelimitedRecord (",")] [FieldOptional()], FileHelpers.
  • , . : Column10, Column11 ..

:

public class CsvToClass
{
    public static string CSharpClassCodeFromCsvFile(string filePath, string delimiter = ",", 
        string classAttribute = "", string propertyAttribute = "")
    {
        if (string.IsNullOrWhiteSpace(propertyAttribute) == false)
            propertyAttribute += "\n\t";
        if (string.IsNullOrWhiteSpace(propertyAttribute) == false)
            classAttribute += "\n";

        string[] lines = File.ReadAllLines(filePath);
        string[] columnNames = lines.First().Split(',').Select(str => str.Trim()).ToArray();
        string[] data = lines.Skip(1).ToArray();

        string className = Path.GetFileNameWithoutExtension(filePath);
        // use StringBuilder for better performance
        string code = String.Format("{0}public class {1} {{ \n", classAttribute, className);

        for (int columnIndex = 0; columnIndex < columnNames.Length; columnIndex++)
        {
            var columnName = Regex.Replace(columnNames[columnIndex], @"[\s\.]", string.Empty, RegexOptions.IgnoreCase);
            if (string.IsNullOrEmpty(columnName))
                columnName = "Column" + (columnIndex + 1);
            code += "\t" + GetVariableDeclaration(data, columnIndex, columnName, propertyAttribute) + "\n\n";
        }

        code += "}\n";
        return code;
    }

    public static string GetVariableDeclaration(string[] data, int columnIndex, string columnName, string attribute = null)
    {
        string[] columnValues = data.Select(line => line.Split(',')[columnIndex].Trim()).ToArray();
        string typeAsString;

        if (AllDateTimeValues(columnValues))
        {
            typeAsString = "DateTime";
        }
        else if (AllIntValues(columnValues))
        {
            typeAsString = "int";
        }
        else if (AllDoubleValues(columnValues))
        {
            typeAsString = "double";
        }
        else
        {
            typeAsString = "string";
        }

        string declaration = String.Format("{0}public {1} {2} {{ get; set; }}", attribute, typeAsString, columnName);
        return declaration;
    }

    public static bool AllDoubleValues(string[] values)
    {
        double d;
        return values.All(val => double.TryParse(val, out d));
    }

    public static bool AllIntValues(string[] values)
    {
        int d;
        return values.All(val => int.TryParse(val, out d));
    }

    public static bool AllDateTimeValues(string[] values)
    {
        DateTime d;
        return values.All(val => DateTime.TryParse(val, out d));
    }

    // add other types if you need...
}

:

class Program
{
    static void Main(string[] args)
    {
        var cSharpClass = CsvToClass.CSharpClassCodeFromCsvFile(@"YourFilePath.csv", ",", "[DelimitedRecord(\",\")]", "[FieldOptional()]");
        File.WriteAllText(@"OutPutPath.cs", cSharpClass);
    }
}

https://github.com/povilaspanavas/CsvToCSharpClass

+5

# , . , , :

public static string CSharpClassCodeFromCsvFile(string filePath)
{
    string[] lines = File.ReadAllLines(filePath);
    string[] columnNames = lines.First().Split(',').Select(str => str.Trim()).ToArray();
    string[] data = lines.Skip(1).ToArray();

    string className = Path.GetFileNameWithoutExtension(filePath);
    // use StringBuilder for better performance
    string code = String.Format("public class {0} {{ \n", className);

    for (int columnIndex = 0; columnIndex < columnNames.Length; columnIndex++)
    {
        code += "\t" + GetVariableDeclaration(data, columnIndex, columnNames[columnIndex]) + "\n";
    }

    code += "}\n";
    return code;
}

public static string GetVariableDeclaration(string[] data, int columnIndex, string columnName)
{
    string[] columnValues = data.Select(line => line.Split(',')[columnIndex].Trim()).ToArray();
    string typeAsString;

    if (AllDateTimeValues(columnValues))
    {
        typeAsString = "DateTime";
    }
    else if (AllIntValues(columnValues))
    {
        typeAsString = "int";
    }
    else if (AllDoubleValues(columnValues))
    {
        typeAsString = "double";
    } 
    else
    {
        typeAsString = "string";
    }

    string declaration = String.Format("public {0} {1} {{ get; set; }}", typeAsString, columnName);
    return declaration;
}

public static bool AllDoubleValues(string[] values)
{
    double d;
    return values.All(val => double.TryParse(val, out d));
}

public static bool AllIntValues(string[] values)
{
    int d;
    return values.All(val => int.TryParse(val, out d));
}

public static bool AllDateTimeValues(string[] values)
{
    DateTime d;
    return values.All(val => DateTime.TryParse(val, out d));
}

// add other types if you need...

, .

+2

CSV, #. TryGetMember DynamicObject .

: # Linq to CSV Dynamic Object

+1

csv2entity :

https://github.com/juwikuang/csv2entity

The installation guide is the readme.md file.

0
source

All Articles