简体   繁体   中英

Write data to a .DAT file with Pipe Delimiter in .NET Core 2.1 version

I was using File Helpers.Net Framework. But when i started using.Net Core 2.1, File Helpers is not compatible. Can someone tell me an alternate was to write a pipe delimiter.Dat file.

Public class product()
{
public int number {get;set;}
public string name {get; set;}
}

I want to write a text file with extension.DAT like the below format

1|John
2|Andrew
3|Stephen

Let me know which is the best option to do this.

Here's one approach: Override ToString() to write each class in the format you want:

public class product()
{
    public int number {get;set;}
    public string name {get; set;}
    public override string ToString()
    {
        return $"{number}|{name}";
    }
}

Then if you have say an IEnumerable<product> called products:

File.WriteAllLines(myFileName, products.Select(p => p.ToString()).ToArray());

The last release of FileHelpers was 3.3.0 which was over a year ago. There has been active development with 3.4.1 branch having a very recent commit https://github.com/MarcosMeli/FileHelpers/tree/3.4.1

In terms of .NET Core support, I know that 2.0 has been retired so it may be worth popping over to their repo and asking the question about 2.1 via an issue as no one else seems to have done.

If you feel like ditching FileHelpers (and I love to use that library myself), then you can make use of the ToString() method mentioned above by @ericj and utilise a products class to bring it together:

public class products() : List<product>
{
    public override string ToString()
    {
        return String.Join(Environment.NewLine, this.ToArray());
    }
}

This is code written here so untested but the theory of it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM