英文单词排序
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Windows;
6 using System.Windows.Controls;
7 using System.Windows.Data;
8 using System.Windows.Documents;
9 using System.Windows.Input;
10 using System.Windows.Media;
11 using System.Windows.Media.Imaging;
12 using System.Windows.Navigation;
13 using System.Windows.Shapes;
14 using System.IO;
15 using Microsoft.Win32;
16
17 namespace WordsSort
18 {
19 /// <summary>
20 /// MainWindow.xaml 的交互逻辑
21 /// </summary>
22 public partial class MainWindow : Window
23 {
24 public MainWindow()
25 {
26 InitializeComponent();
27 }
28
29 private void btnOpen_Click(object sender, RoutedEventArgs e)
30 {
31 OpenFileDialog openFileDialog = new OpenFileDialog();
32 openFileDialog.Filter = "Text Files|*.txt";
33 openFileDialog.Title = "打开文件";
34 if (openFileDialog.ShowDialog() == true)
35 {
36 if (File.Exists(openFileDialog.FileName))
37 {
38 Cursor oldCursor = this.Cursor;
39 try
40 {
41 List<string> wordsList = new List<string>();
42 using (StreamReader sr = new StreamReader(openFileDialog.FileName, System.Text.Encoding.Default))
43 {
44 string line;
45 while ((line = sr.ReadLine()) != null)
46 {
47 if (!string.IsNullOrEmpty(line))
48 {
50 wordsList.Add(line);
51 }
52 }
53 }
54 this.Cursor = Cursors.Wait;
55 WriteWords(wordsList, openFileDialog.FileName);
56
57 }
58 catch (Exception ex)
59 {
60 throw (ex);
61 }
62 finally
63 {
64 this.Cursor = oldCursor;
65 }
66
67 }
68
69 }
70 }
71
72 /// <summary>
73 /// 写排序文件
74 /// </summary>
75 /// <param name="wordsList">单词列表</param>
76 /// <param name="oldFileName">旧文件名</param>
77 private void WriteWords(List<string> wordsList, string oldFileName)
78 {
79 int index = oldFileName.LastIndexOf('.');
80 string newFileName = oldFileName.Remove(index) + "排序.txt";
81 if (File.Exists(newFileName))
82 {
83 File.Delete(newFileName);
84 }
85 wordsList.Sort();
86 FileStream fs = new FileStream(newFileName, FileMode.Append, FileAccess.Write);
87 string firstString = "";
88 foreach (string word in wordsList)
89 {
90 if (!string.Equals(word[0].ToString(), firstString,StringComparison.OrdinalIgnoreCase))
91 {
92 fs.Write(Encoding.Default.GetBytes("\r\n"), 0, 2);
93 firstString = word[0].ToString();
94 }
95
96 fs.Write(Encoding.Default.GetBytes(word + "\r\n"), 0, Encoding.Default.GetByteCount(word) + 2);
97
98 }
99 fs.Close();
100 }
101
102
103 }
104 }