-2

enter image description here

I need to convert .txt file to j son file in C# console app

Machavity
  • 30,841
  • 27
  • 92
  • 100
Mathembi
  • 17
  • 1
  • 5

2 Answers2

1

If you have such a text file

1|name1|lastname1|test1@test.com|127.0.0.1

2|name2|lastname2|test2@test.com|127.0.0.2

3|name3|lastname3|test3@test.com|127.0.0.3

You can convert it to json with the following code

var filename = "C:\\1.txt";
var lines = File.ReadAllLines(filename);

var model = lines.Select(p => new
{
    Id = p.Split("|")[0],
    FirstName = p.Split("|")[1],
    LastName = p.Split("|")[2],
    Email = p.Split("|")[3],
    Ip = p.Split("|")[4],
});
var json = JsonSerializer.Serialize(model);
Saman Azadi
  • 116
  • 1
  • 6
0

You can make class or struct User, make constructor for this and deserialize this class. I prefer to use classes.

Class example:

class User
{
  public int id;
  public string name;
  public string surname;
  public string email;
  public string gender;
  public string IPAddress;
}
string split = YOUR_TXT_FILE_STRING.Split('|'); //Splitting file
User user = new User(split[0], split[1], split[2], split[3], split[4, split[5]]);
string output = JsonSerializer.Serialize(user, true); //Deserializing class

And now you can write output into text file again

Usefull links:

It is easiest way you can do.

cyberfrogg
  • 116
  • 2
  • 8