在 C# 中按字母顺序对文本文件进行排序
本文关键字:文件 文本 排序 顺序 | 更新日期: 2023-09-27 18:35:56
我正在尝试用 C# 编写一个程序,该程序对包含姓氏后跟逗号和名字的文本文件进行排序。我怎样才能根据字母顺序编写文本文件 n 姓氏。
有很多选项,具体取决于细节。 未经测试,但这样的事情应该很接近。
string inFile = @"C:'someInFile.txt";
string outFile = @"C:'someOutFile.txt";
var contents = File.ReadAllLines(inFile);
Array.Sort(contents);
File.WriteAllLines(outFile, contents)
这是 VB.NET,但翻译应该很容易:
Public Sub FileCreateReadAndSort()
'Read data from database and write to unsorted text file
Dim dv As DataView = DataLib.QryToData("select * from gen where rn<10", EnumLib.DBList.Gen, EnumLib.DataObj.DataView)
Dim S As String = ""
For i As Integer = 0 To dv.Count - 1
With dv(i)
S = S & RTrim(.Item("surname")) & ", " & RTrim(.Item("name")) & vbCrLf
End With
Next
Dim SW As IO.StreamWriter = New IO.StreamWriter("c:'temp'fileOriginal.txt")
SW.Write(S)
SW.Flush()
SW.Close()
SW.Dispose()
'read in unsorted text file
Dim SR As IO.StreamReader = New IO.StreamReader("c:'temp'fileOriginal.txt")
Dim S2 As ArrayList = New ArrayList
Do While Not SR.EndOfStream
S2.Add(SR.ReadLine)
Loop
'sort file lines and write to sorted file
Dim S3 As Array = S2.ToArray
Array.Sort(S3)
Dim SW2 As IO.StreamWriter = New IO.StreamWriter("c:'temp'fileSorted.txt")
For i As Integer = 0 To S3.Length - 1
SW2.Write(S3(i) & vbCrLf)
Next i
SW2.Flush()
SW2.Close()
SW2.Dispose()
End Sub
希望这有帮助!
戴夫
你可以
使用它,
FileStream readerStream = new FileStream(@"Desktop'Source'text.txt", FileMode.Open);
string[] content = null;
//Read the content
using (StreamReader reader = new StreamReader(readerStream))
{
content = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
//Remove the entries in the file
readerStream.SetLength(0);
}
FileStream writerStream = new FileStream(@"Desktop'Source'text.txt", FileMode.OpenOrCreate);
using (StreamWriter writer = new StreamWriter(writerStream))
{
//Sort the content and write back to the same file
Array.Sort(content);
writer.Write(string.Join(Environment.NewLine, content));
}