本筆記摘抄自:https://www.cnblogs.com/liyangLife/p/4797583.html,記錄一下學習程序以備后續查用,
一、檔案系統
1.1檔案系統類的介紹
檔案操作類大都在System.IO命名空間里,FileSystemInfo類是所有檔案系統類的基類,FileInfo與File表示檔案系統中的檔案,DirectoryInfo與Directory
表示檔案系統中的檔案夾,Path表示檔案系統中的路徑,DriveInfo提供對有關驅動器資訊的訪問,
注意,XXXInfo與XXX類的區別是:XXX是靜態類,XXXInfo類可以實體化,還有個較為特殊的類System.MarshalByRefObject允許在支持遠程處理的
應用程式中跨應用程式域邊界訪問物件,
1.2FileInfo與File類
class Program { static void Main(string[] args) { #region FileInfo與File類 //創建檔案 FileInfo file = new FileInfo(@"E:\學習筆記\C#\Test.txt"); FileStream fs = file.Create(); //關閉檔案流,這個很重要, fs.Close(); Console.WriteLine("創建時間:" + file.CreationTime); Console.WriteLine("檔案路徑:" + file.DirectoryName); //打開追加流 StreamWriter sw = file.AppendText(); //追加資料 sw.Write("科比·布萊恩特"); //釋放資源,關閉檔案, sw.Dispose(); //移動 File.Move(file.FullName, @"E:\學習筆記\Test.txt"); Console.WriteLine("檔案創建并操作完成,"); Console.Read(); #endregion } }View Code
運行結果如下:

1.3DirectoryInfo與Directory類
class Program { static void Main(string[] args) { #region FileInfo與File類 ////創建檔案 //FileInfo file = new FileInfo(@"E:\學習筆記\C#\Test.txt"); //FileStream fs = file.Create(); ////關閉檔案流,這個很重要, //fs.Close(); //Console.WriteLine("創建時間:" + file.CreationTime); //Console.WriteLine("檔案路徑:" + file.DirectoryName); ////打開追加流 //StreamWriter sw = file.AppendText(); ////追加資料 //sw.Write("科比·布萊恩特"); ////釋放資源,關閉檔案, //sw.Dispose(); ////移動 //File.Move(file.FullName, @"E:\學習筆記\Test.txt"); //Console.WriteLine("檔案創建并操作完成,"); //Console.Read(); #endregion #region DirectoryInfo與Directory類 //創建檔案夾 DirectoryInfo directory = new DirectoryInfo(@"E:\學習筆記\C#\Test"); directory.Create(); Console.WriteLine("父檔案夾:" + directory.Parent.FullName); //輸出父目錄下的所有檔案夾與檔案 FileSystemInfo[] infos = directory.Parent.GetFileSystemInfos(); foreach (FileSystemInfo info in infos) { Console.WriteLine(info.Name); } //洗掉檔案夾 Directory.Delete(directory.FullName); Console.WriteLine("檔案夾創建并操作完成,"); Console.Read(); #endregion } }View Code
運行結果如下:

1.4Path類
class Program { static void Main(string[] args) { #region Path類 //連接 Console.WriteLine(Path.Combine(@"E:\學習筆記\C#", @"Test.txt")); Console.WriteLine("平臺特定的字符:" + Path.DirectorySeparatorChar); Console.WriteLine("平臺特定的替換字符:" + Path.AltDirectorySeparatorChar); Console.Read(); #endregion } }View Code
運行結果如下:

1.5DriveInfo類
class Program { static void Main(string[] args) { #region DriveInfo類 DriveInfo[] drives = DriveInfo.GetDrives(); foreach (DriveInfo drive in drives) { if (drive.IsReady) { Console.WriteLine("驅動器名稱:" + drive.Name); Console.WriteLine("驅動器型別:" + drive.DriveFormat); Console.WriteLine("總容量:" + drive.TotalFreeSpace); Console.WriteLine("可用容量:" + drive.AvailableFreeSpace + "\n"); } } Console.Read(); #endregion } }View Code
運行結果如下:

二、檔案操作
2.1檔案的移動、復制、洗掉
class Program { static void Main(string[] args) { #region 檔案的移動、復制、洗掉 string path = @"E:\學習筆記\Test.txt"; File.WriteAllText(path, "測驗資料"); Console.WriteLine("檔案已寫入,"); File.Move(path, @"E:\學習筆記\C#\Test.txt"); Console.WriteLine("檔案已移動,"); File.Copy(@"E:\學習筆記\C#\Test.txt", path); Console.WriteLine("檔案已復制,"); File.Delete(@"E:\學習筆記\C#\Test.txt"); Console.WriteLine("檔案已洗掉,"); Console.Read(); #endregion } }View Code
2.2判斷路徑是檔案還是檔案夾
class Program { static void Main(string[] args) { #region 判斷路徑是檔案還是檔案夾 IsFile(@"E:\學習筆記\Test.txt"); IsFile(@"E:\學習筆記\"); IsFile(@"E:\學習筆記\XXX"); Console.Read(); #endregion } /// <summary> /// 判斷路徑是檔案還是檔案夾 /// </summary> /// <param name="path"></param> static void IsFile(string path) { if (File.Exists(path)) { Console.WriteLine("這是個檔案,"); } else if (Directory.Exists(path)) { Console.WriteLine("這是個檔案夾,"); } else { Console.WriteLine("路徑不存在,"); } } }View Code
運行結果如下:

三、檔案讀寫與資料流
3.1檔案讀取
class Program { static void Main(string[] args) { #region 檔案讀取 string path = @"E:\學習筆記\Test.txt"; byte[] bytes = File.ReadAllBytes(path); Console.WriteLine("ReadAllBytes讀二進制:"); foreach (byte b in bytes) { Console.Write((char)b); } Console.WriteLine(Environment.NewLine); string[] strs = File.ReadAllLines(path, Encoding.UTF8); Console.WriteLine("ReadAllLines讀所有行:"); foreach (string s in strs) { Console.WriteLine(s + "\n"); } string str = File.ReadAllText(path, Encoding.UTF8); Console.WriteLine("ReadAllText讀所有行:\n" + str); Console.Read(); #endregion } }View Code
運行結果如下:

3.2檔案寫入
class Program { static void Main(string[] args) { #region 檔案寫入 string path = @"E:\學習筆記\Test.txt"; File.WriteAllBytes(path, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); //寫入二進制 Console.WriteLine("WriteAllBytes寫入二進制成功,"); string[] array = { "123", "456", "789" }; File.WriteAllLines(path, array, Encoding.UTF8); //寫入所有行 Console.WriteLine("WriteAllLines寫入所有行成功,"); File.WriteAllText(path, "Hello World", Encoding.UTF8); //寫入字串 Console.WriteLine("WriteAllText寫入字串成功,\n"); Console.Read(); #endregion } }View Code
3.3資料流
FileStream:檔案流,可以讀寫二進制檔案,
StreamReader:流讀取器,使其以一種特定的編碼從位元組流中讀取字符,
StreamWriter:流寫入器,使其以一種特定的編碼向流中寫入字符,
BufferedStream:緩沖流,給另一流上的讀寫操作添加一個緩沖層,
3.3.1使用FileStream讀寫二進制檔案
class Program { static void Main(string[] args) { #region 使用FileStream讀寫二進制檔案 string path = @"E:\學習筆記\C#\Test.txt"; //以寫檔案的方式創建檔案 FileStream file = new FileStream(path, FileMode.CreateNew, FileAccess.Write); string str = "科比·布萊恩特"; byte[] bytes = Encoding.Unicode.GetBytes(str); //寫入二進制 file.Write(bytes, 0, bytes.Length); file.Dispose(); Console.WriteLine("寫入資料成功!!!"); //以讀檔案的方式打開檔案 file = new FileStream(path, FileMode.Open, FileAccess.Read); byte[] temp = new byte[bytes.Length]; //讀取二進制 file.Read(temp, 0, temp.Length); Console.WriteLine("讀取資料:" + Encoding.Unicode.GetString(temp)); file.Dispose(); Console.Read(); #endregion } }View Code
運行結果如下:

3.3.2StreamWriter與StreamReader
使用StreamWriterStreamReader就不用擔心文本檔案的編碼方式,所以它們很適合讀寫文本檔案,
class Program { static void Main(string[] args) { #region StreamWriter與StreamReader string path = @"E:\學習筆記\C#\Test1.txt"; //以寫檔案的方式創建檔案 FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write); StreamWriter sw = new StreamWriter(file); sw.WriteLine("科比·布萊恩特"); sw.Dispose(); Console.WriteLine("寫入資料成功!!!"); //以讀檔案的方式打開檔案 file = new FileStream(path, FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(file); Console.WriteLine("讀取資料:" + sr.ReadToEnd()); sr.Dispose(); Console.Read(); #endregion } }View Code
運行結果如下:

四、記憶體映射檔案
MemoryMappedFile類(.NET4新增):
應用程式需要頻繁地或隨機地訪問檔案時,最好使用MemoryMappedFile類(映射記憶體的檔案),使用這種方式允許把檔案的一部分或者全部加載到一段
虛擬記憶體上,這些檔案內容會顯示給應用程式,就好像這個檔案包含在應用程式的主記憶體中一樣,
class Program { static void Main(string[] args) { #region 記憶體映射檔案 MemoryMappedFile mmFile = MemoryMappedFile.CreateFromFile(@"E:\學習筆記\C#\Test2.txt", FileMode.OpenOrCreate, "MapName", 1024 * 1024); //記憶體映射檔案的視圖 //或使用資料流操作記憶體檔案MemoryMappedViewStream stream = mmFile.CreateViewStream(); MemoryMappedViewAccessor mmViewAccessor = mmFile.CreateViewAccessor(); string str = "科比·布萊恩特"; int length = Encoding.UTF8.GetByteCount(str); //寫入資料 mmViewAccessor.WriteArray<byte>(0, Encoding.UTF8.GetBytes(str), 0, length); byte[] bytes = new byte[length]; mmViewAccessor.ReadArray<byte>(0, bytes, 0, bytes.Length); Console.WriteLine(Encoding.UTF8.GetString(bytes)); //釋放資源 mmFile.Dispose(); Console.Read(); #endregion } }View Code
運行結果如下:

五、檔案安全
5.1ACL介紹
ACL是存在于計算機中的一張表(訪問控制表),它使作業系統明白每個用戶對特定系統物件--例如檔案目錄或單個檔案的存取權限,每個物件擁有一個在
訪問控制表中定義的安全屬性,每個系統用戶對于這張表擁有一個訪問權限,最一般的訪問權限包括讀檔案(包括所有目錄中的檔案)、寫一個或多個檔案
和執行一個檔案(如果它是一個可執行檔案或者是程式的時候),
5.2讀取檔案的ACL
class Program { static void Main(string[] args) { #region 讀取檔案的ACL FileStream file = new FileStream(@"E:\學習筆記\Test.txt", FileMode.Open, FileAccess.Read); //得到檔案訪問控制屬性 FileSecurity filesec = file.GetAccessControl(); //輸出檔案的訪問控制項 foreach (FileSystemAccessRule filerule in filesec.GetAccessRules(true, true, typeof(NTAccount))) { Console.WriteLine(filerule.AccessControlType + "--" + filerule.FileSystemRights + "--" + filerule.IdentityReference); } file.Dispose(); Console.Read(); #endregion } }View Code
運行結果如下:

5.3讀取檔案夾的ACL
class Program { static void Main(string[] args) { #region 讀取檔案夾的ACL DirectoryInfo dir = new DirectoryInfo(@"E:\學習筆記\C#\"); //得到檔案訪問控制屬性 DirectorySecurity filesec = dir.GetAccessControl(); //輸出檔案的訪問控制項 foreach (FileSystemAccessRule filerule in filesec.GetAccessRules(true, true, typeof(NTAccount))) { Console.WriteLine(filerule.AccessControlType + "--" + filerule.FileSystemRights + "--" + filerule.IdentityReference); } Console.Read(); #endregion } }View Code
運行結果如下:

5.4修改ACL
class Program { static void Main(string[] args) { #region 修改ACL FileStream file = new FileStream(@"E:\學習筆記\Test.txt", FileMode.Open, FileAccess.Read); //得到檔案訪問控制屬性 FileSecurity filesec = file.GetAccessControl(); //輸出檔案訪問控制項 PrintACL(filesec.GetAccessRules(true, true, typeof(NTAccount))); FileSystemAccessRule rule = new FileSystemAccessRule ( new NTAccount(@"AtomyStudio\Administrator"), //計算機賬戶名 FileSystemRights.Delete, //操作權限 AccessControlType.Allow //能否訪問受保護的物件 ); filesec.AddAccessRule(rule); //增加ACL項 PrintACL(filesec.GetAccessRules(true, true, typeof(NTAccount))); //輸出檔案訪問控制項 filesec.RemoveAccessRule(rule); //移除ACL項 PrintACL(filesec.GetAccessRules(true, true, typeof(NTAccount))); //輸出檔案訪問控制項 file.Dispose(); Console.Read(); #endregion } }View Code
運行結果如下:

六、讀寫注冊表
6.1注冊表介紹
Windows注冊表是幫助Windows控制硬體、軟體、用戶環境和Windows界面的一套資料檔案,運行regedit可以看到有5個注冊表配置單元(實際有7個):
HKEY-CLASSES-ROOT: 檔案關聯和COM資訊
HKEY-CURRENT-USER: 用戶輪廓
HKEY-LOCAL-MACHINE: 本地機器系統全域配置子鍵
HKEY-USERS: 已加載用戶輪廓子鍵
HKEY-CURRENT-CONFIG: 當前硬體配置
6.2.NET操作注冊表的類
在.NET中提供了Registry類、RegistryKey類來實作對注冊表的操作,
6.2.1Registry類
封裝了注冊表的七個基本主鍵:
Registry.ClassesRoot 對應于HKEY_CLASSES_ROOT主鍵
Registry.CurrentUser 對應于HKEY_CURRENT_USER主鍵
Registry.LocalMachine 對應于HKEY_LOCAL_MACHINE主鍵
Registry.User 對應于HKEY_USER主鍵
Registry.CurrentConfig 對應于HEKY_CURRENT_CONFIG主鍵
Registry.DynDa 對應于HKEY_DYN_DATA主鍵
Registry.PerformanceData 對應于HKEY_PERFORMANCE_DATA主鍵
6.2.2RegistryKey類
封裝了對注冊表的基本操作,包括讀取、寫入,洗掉,
1)讀取的函式:
OpenSubKey() 主要是打開指定的子鍵
GetSubKeyNames() 獲得主鍵下面的所有子鍵的名稱,它的回傳值是一個字串陣列,
GetValueNames() 獲得當前子鍵中的所有的鍵名稱,它的回傳值也是一個字串陣列,
GetValue() 指定鍵的鍵值,
2)寫入的函式:
CreateSubKey() 增加一個子鍵
SetValue() 設定一個鍵的鍵值
3)洗掉的函式:
DeleteSubKey() 洗掉一個指定的子鍵
DeleteSubKeyTree() 洗掉該子鍵以及該子鍵以下的全部子鍵
6.3示例
class Program { static void Main(string[] args) { #region 讀寫注冊表 string path = @"SOFTWARE\Microsoft\Internet Explorer\Extension Compatibility"; //以只讀方式 RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(path, true); if (registryKey != null) { Console.WriteLine(registryKey.Name + "--" + registryKey.SubKeyCount + "--" + registryKey.ValueCount); string subRegistryKey = Guid.NewGuid().ToString(); //增加一個子鍵 registryKey.CreateSubKey(subRegistryKey); RegistryKey newRegistryKey = Registry.LocalMachine.OpenSubKey(path + @"\" + subRegistryKey, true); //設定一個鍵的鍵值 newRegistryKey.SetValue("姓名", "科比"); //設定一個鍵的鍵值 newRegistryKey.SetValue("鍵名", "布萊恩特"); Console.WriteLine(registryKey.Name + "--" + registryKey.SubKeyCount + "--" + registryKey.ValueCount); registryKey.Close(); newRegistryKey.Close(); } Console.Read(); #endregion } }View Code
運行結果生成值為:

七、讀寫獨立的存盤器
7.1IsolatedStorageFile類
使用IsolatedStorageFile類可以讀寫獨立的存盤器,
獨立的存盤器可以看成一個虛擬磁盤,在其中可以保存只由創建他們的應用程式或其應用程式實體共享的資料項,
獨立的存盤器的訪問型別有兩種:第一種是一個應用程式的多個實體在同一個獨立存盤器中作業,第二種是一個應用程式的多個實體在各自不同的獨立存
儲器中作業,
7.2示例
class Program { static void Main(string[] args) { #region 讀寫獨立的存盤器 //寫檔案 IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(@"Test.txt", FileMode.Create, FileAccess.Write); string str = "科比·布萊恩特"; byte[] bytes = Encoding.UTF8.GetBytes(str); //寫資料 fileStream.Write(bytes, 0, bytes.Length); fileStream.Dispose(); //讀檔案 IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForDomain(); string[] fileNames = file.GetFileNames(@"Test.txt"); foreach (string fileName in fileNames) { Console.WriteLine(fileName); fileStream = new IsolatedStorageFileStream(fileName, FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(fileStream); Console.WriteLine("讀取檔案:" + sr.ReadToEnd()); sr.Dispose(); //洗掉檔案 file.DeleteFile(fileName); } file.Dispose(); Console.WriteLine("OK!"); Console.Read(); #endregion } }View Code
運行結果如下:

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/84745.html
標籤:C#
上一篇:C# compare different Encoding pattern between UTF8 and UTF32 based on Md5
下一篇:C#登出系統并清除Cookie
