从列表保存到txt我想让我的程序从两个文本文件读取到一个列表中。列表已排序并清除了重复项。我希望列表保存(排序和清理后)到一个txt文件。但是当我查看结果txt文件时,我发现了这条消息:System.Collections.Generic.List`1[System.String]有谁知道如何解决这个错误?这是我的代码:使用系统;使用System.Collections.Generic;使用System.Linq;使用系统文本;使用System.IO;namespaceUniqpass{classProgram{staticvoidMain(string[]args){Stringpath="C:\DocumentsandSettings\Bektas\Desktop\test\";Stringpath2="C:\DocumentsandSettings\Bektas\Desktop\test\";SaveString="C:\DocumentsandSettings\Bektas\Desktop\test\output.txt";字符串文件="text1.txt";Stringfile2="text2.txt";try{//读取TxT1Listpass1=newList();StreamReadersr1=newStreamReader(path+file);while(sr1.Peek()>-1){pass1.Add(sr1.ReadLine());}sr1.Close();//读入TxT2StreamReadersr2=newStreamReader(path2+file2);while(sr2.Peek()>-1){pass1.Add(sr2.ReadLine());}sr2.Close();列表outputList=pass1.Distinct().ToList();outputList.Sort();outputList.ForEach(C控制台.WriteLine);StreamWriter文件=newSystem.IO.StreamWriter(speichern);file.WriteLine(ausgabeListe);文件.关闭();}catch(Exception){Console.WriteLine("Error");}Console.ReadKey();有一个方便的小方法File.WriteAllLines-无需自己打开StreamWriter:在.net4中:File.WriteAllLines(speichern,ausgabeListe);在.net3.5中:File.WriteAllLines(speichern,ausgabeListe.ToArray());同样,您可以将读取逻辑替换为File.ReadAllLines,FileReadAllLines返回一个字符串数组(如果您想要一个列表,则返回ToList())因此,在实践中,您的完整代码可以简化为://InputListdata=File.ReadAllLines(pfad+datei).Concat(File.ReadAllLines(pfad2+datei2)).Distinct().ToList();//处理数据.Sort();//输出数据。ForEach(Console.WriteLine);File.WriteAllLines(speichern,数据);此行被写入列表的ToString表示形式,导致您获得以下文本行:StreamWriterfile=newSystem.IO.StreamWriter(speichern);file.WriteLine(ausgabeListe);文件.关闭();相反,您想写每一行。StreamWriter文件=newSystem.IO.StreamWriter(speichern);ausgabeListe.ForEach(file.WriteLine);文件.关闭();遍历列表,单独写入每一行:StreamWriterfile=newSystem.IO.StreamWriter(speichern);foreach(ausgabeListe中的字符串行)file.WriteLine(行);文件.关闭();您正在将列表对象写入文件,因此您可以看到类型名称。当您使用ForEach写入控制台时,您需要遍历ausgabeListe,为列表中的每个项目调用WriteLine()。StreamWriter文件=newSystem.IO.StreamWriter(speichern);foreach(ausgabeListe中的字符串x)file.WriteLine(x);文件.关闭();我正在使用下面的LINQ将每一行写入一个文本文件。以上就是C#学习教程:List保存到txt分享的全部内容,如果对你有用,还需要了解更多C#学习教程,希望大家多多关注——varmyList=newList{"你好“,“世界”};使用(varfile=newStreamWriter("myfile.txt")){myList.ForEach(v=>file.WriteLine(v));}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
