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"); //測試產生新的Txt檔案 List<string> list = mgr.ReadTextFileToList(@"C:\test.txt");//記取字串 foreach (string s in list) Console.WriteLine(s); //顯示出來′ Console.ReadKey(); //按′任一鍵關閉Console /* * 結果:
* JUQI\ASPNET JUQI\capable JUQI\Guest JUQI\itd0300166 JUQI\IUSR_PLSH166 JUQI\IWAM_PLSH166 JUQI\SUPPORT_388945a0 * * */ } } public class test { /// <summary> /// 擷取本機上的使用者帳戶
/// </summary> /// <param name="domainName"></param> /// <returns></returns> 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()); //domainName = mo.GetPropertyValue("Domain").ToString(); } return lstNames; } //將List轉換為TXT檔案 public void WriteListToTextFile(List<string> list, string txtFile) { //建立一個檔案流,用以寫入或者建立一個StreamWriter FileStream fs = new FileStream(txtFile, FileMode.OpenOrCreate, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); sw.Flush(); // 使用StreamWriter來往檔案中寫入內容 sw.BaseStream.Seek(0, SeekOrigin.Begin); for (int i = 0; i < list.Count; i++) sw.WriteLine(list[i]); //關閉此檔案t sw.Flush(); sw.Close(); fs.Close(); } //讀取文字檔轉換為List 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); //使用StreamReader類來讀取檔案 sr.BaseStream.Seek(0, SeekOrigin.Begin); // 從資料流中讀取每一行,直到檔案的最後一行 string tmp = sr.ReadLine(); while (tmp != null) { list.Add(tmp); tmp = sr.ReadLine(); } //關閉此StreamReader對象 sr.Close(); fs.Close(); return list; } } }