C# 使用List泛型读取和保存文本文件
发布时间:2010年03月06日点击数:
次佚名
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- using System.Management;
- using System.IO;
-
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- test mgr = new test();
- mgr.WriteListToTextFile(mgr.GetUserNames(), @"c:\test.txt");
- List<string> list = mgr.ReadTextFileToList(@"C:\test.txt");
- foreach (string s in list) Console.WriteLine(s);
- Console.ReadKey();
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
- }
- public class test
- {
-
-
-
-
-
-
- public List<String> GetUserNames()
- {
- ManagementClass mcs = new ManagementClass("Win32_UserAccount");
- ManagementObjectCollection moc = mcs.GetInstances();
- List<String> lstNames = new List<string>();
- foreach (ManagementObject mo in moc)
- {
- lstNames.Add(Environment.UserDomainName + "\\" + mo.GetPropertyValue("Name").ToString());
-
- }
- return lstNames;
- }
-
-
-
- public void WriteListToTextFile(List<string> list, string txtFile)
- {
-
- FileStream fs = new FileStream(txtFile, FileMode.OpenOrCreate, FileAccess.Write);
- StreamWriter sw = new StreamWriter(fs);
- sw.Flush();
-
- sw.BaseStream.Seek(0, SeekOrigin.Begin);
- for (int i = 0; i < list.Count; i++) sw.WriteLine(list[i]);
-
- sw.Flush();
- sw.Close();
- fs.Close();
- }
-
-
-
- public List<string> ReadTextFileToList(string fileName)
- {
- FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
- List<string> list = new List<string>();
- StreamReader sr = new StreamReader(fs);
-
- sr.BaseStream.Seek(0, SeekOrigin.Begin);
-
- string tmp = sr.ReadLine();
- while (tmp != null)
- {
- list.Add(tmp);
- tmp = sr.ReadLine();
- }
-
- sr.Close();
- fs.Close();
- return list;
- }
- }
-
- }