I need to convert .txt file to j son file in C# console app
Asked
Active
Viewed 4,003 times
-2
-
and what have you ***tried yourself so far***? please show your current efforts and share what specific problems you have. – Franz Gleichmann May 23 '21 at 11:05
-
What have you tried so far? Also, please don't post a problem statement as an image. – Adrian S May 23 '21 at 11:06
2 Answers
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:
- https://learn.microsoft.com/ru-ru/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0
- https://learn.microsoft.com/ru-ru/dotnet/api/system.io.file.writealltext?view=net-5.0
It is easiest way you can do.

cyberfrogg
- 116
- 2
- 8