从List<T>保存到txt文件

30
我希望我的程序能够从两个文本文件中读取数据,并将它们放入一个List<T>中。这个List<T>会进行排序并清除重复项。
我希望在对List<T>进行排序和去重后,将其保存到txt文件中。但当我查看结果txt文件时,发现出现了以下信息:

System.Collections.Generic.List`1[System.String]

请问有人知道如何解决这个错误吗?
以下是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Uniqpass
{
    class Program
    {
        static void Main(string[] args)
        {

            String pfad = "C:\\Dokumente und Einstellungen\\Bektas\\Desktop\\test\\";
            String pfad2 = "C:\\Dokumente und Einstellungen\\Bektas\\Desktop\\test\\";
            String speichern = "C:\\Dokumente und Einstellungen\\Bektas\\Desktop\\test\\ausgabe.txt";
            String datei = "text1.txt";
            String datei2 = "text2.txt";

            try
            {

                //Einlesen TxT 1
                List<String> pass1 = new List<String>();
                StreamReader sr1 = new StreamReader(pfad + datei);
                while (sr1.Peek() > -1)
                {

                    pass1.Add(sr1.ReadLine());
                }
                sr1.Close();
                //Einlesen TxT 2
                StreamReader sr2 = new StreamReader(pfad2 + datei2);
                while (sr2.Peek() > -1)
                {
                    pass1.Add(sr2.ReadLine());
                }
                sr2.Close();

                List<String> ausgabeListe = pass1.Distinct().ToList();
                ausgabeListe.Sort();

                ausgabeListe.ForEach(Console.WriteLine);

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


            }
            catch (Exception)
            {
                Console.WriteLine("Error");
            }

            Console.ReadKey();
        }
    }
}
7个回答

74

有一个方便的小方法File.WriteAllLines -- 无需自己打开StreamWriter:

在 .net 4 中:

File.WriteAllLines(speichern, ausgabeListe);
在.NET 3.5中:
File.WriteAllLines(speichern, ausgabeListe.ToArray());
同样地,你可以使用File.ReadAllLines替换你的读取逻辑,它会返回一个字符串数组(如果你需要一个List<string>,可以在其上使用ToList())。
因此,事实上,你的完整代码可以简化为:
// 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);

2
这个答案很棒,因为它将可能需要几行代码的操作简化成了一行。 - Free2Rhyme2k
@Free2Rhyme2k:是的,通常意味着代码行数越少,出现的错误也就越少。 - Heinzi

10

就是这行代码将List对象转换为ToString表示形式,生成了你获得的文本行:

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

相反,您希望逐行编写。

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

1

遍历列表,逐行写入:

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

1
请尝试下面的代码:
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----------------");

0
我正在使用LINQ将每行写入文本文件,代码如下:
var myList=new List<string>
{
    "Hello",
    "World"
};
using (var file = new StreamWriter("myfile.txt"))
{
    myList.ForEach(v=>file.WriteLine(v));
}

0

你正在将列表对象写入文件,因此你会看到类型名称。

就像你使用ForEach将内容写入控制台一样,你需要迭代ausgabeListe,对列表中的每个项目调用WriteLine()


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

你能否将变量名称,如“speichern”和“ausgabeListe”改为更易于理解的名称? - Weifeng

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接