Saving from List<T> to txt

强颜欢笑 提交于 2019-11-27 14:18:08

There's a handy little method File.WriteAllLines -- no need to open a StreamWriter yourself:

In .net 4:

File.WriteAllLines(speichern, ausgabeListe);

In .net 3.5:

File.WriteAllLines(speichern, ausgabeListe.ToArray());

Likewise, you could replace your reading logic with File.ReadAllLines, which returns an array of strings (use ToList() on that if you want a List<string>).

So, in fact, your complete code could be reduced to:

// Input
List<String> data = File.ReadAllLines(pfad + datei)
    .Concat(File.ReadAllLines(pfad2 + datei2))
    .Distinct().ToList();

// Processing
data.Sort(); 

// Output
data.ForEach(Console.WriteLine); 
File.WriteAllLines(speichern, data);

It's this line which writes the ToString representation of the List, resulting into the text line you got:

StreamWriter file = new System.IO.StreamWriter(speichern);
file.WriteLine(ausgabeListe);
file.Close();

Instead you want to write each line.

StreamWriter file = new System.IO.StreamWriter(speichern);
ausgabeListe.ForEach(file.WriteLine);
file.Close();

Loop through the list, writing each line individually:

StreamWriter file = new System.IO.StreamWriter(speichern);
foreach(string line in ausgabeListe)
    file.WriteLine(line);
file.Close();

You are writing the list object into the file, so you see the type name.

Just as you are using ForEach to write the contents to the Console, you need to iterate over ausgabeListe, calling WriteLine() for each item in the list.

StreamWriter file = new System.IO.StreamWriter(speichern);
foreach(string x in ausgabeListe)
    file.WriteLine(x);
file.Close();

I am using the LINQ like below to write each line to text file.

var myList=new List<string>
{
    "Hello",
    "World"
};
using (var file = new StreamWriter("myfile.txt"))
{
    myList.ForEach(v=>file.WriteLine(v));
}
Prabhakaran M

Try the code below:

StreamWriter writer = new StreamWriter("C:\\Users\\Alchemy\\Desktop\\c#\\InputFileFrmUser.csv");
list = new List<Product>() { new Product() { ProductId=1, Name="Nike 12N0",Brand="Nike",Price=12000,Quantity=50},
        new Product() { ProductId =2, Name = "Puma 560K", Brand = "Puma", Price = 120000, Quantity = 55 },
        new Product() { ProductId=3, Name="WoodLand V2",Brand="WoodLand",Price=21020,Quantity=25},
        new Product() { ProductId=4, Name="Adidas S52",Brand="Adidas",Price=20000,Quantity=35},
        new Product() { ProductId=5, Name="Rebook SPEED2O",Brand="Rebook",Price=1200,Quantity=15}};

foreach (var x in list) {
    string wr = x.ProductId + " " + x.Name + "" + x.Brand + " " + x.Quantity + " " + x.Price;
    writer.Flush();
    writer.WriteLine(wr);

}
Console.WriteLine("--------ProductList Updated SucessFully----------------");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!