C# 常用的文件IO操作
目錄
?
一、IO流
1.文件夾操作?Directory類
2.文件操作 File類
3.路徑操作 Path類
4.讀取文件?StreamReader類
5.寫入文件?StreamWriter類
二、動態鏈接庫kernel32
1.寫入文件
2.讀取文件
一、IO流
注意:
路徑有3種方式,當前目錄下的相對路徑、當前工作盤的相對路徑、絕對路徑。以C:\Temp\Directory為例(假定當前工作目錄為C:\Temp)。“Directory”,“\Temp\Directory”,“C:\Temp\Directory”都表示C:\Temp\Directory。
另外,在C#中 “\”是特殊字符,要表示它的話需要使用“\\”。由于這種寫法不方便,C#語言提供了@對其簡化。只要在字符串前加上@即可直接使用“\”。所以上面的路徑在C#中應該表示為“Directory”,@“\Temp\Directory”,@“C:\Temp\Directory”。
1.文件夾操作?Directory類
1.判斷文件夾是否存在
Directory.Exists(filePath);//判斷文件夾是否存在2.獲取目錄下指定類型的文件
Directory.GetFiles(filePath, "*.ttf.meta", SearchOption.TopDirectoryOnly);//獲取指定格式的文件通配符說明:
* :匹配在該位置的零個或多個字符
? :匹配在該位置的零個或一個字符
通配符以外的字符為原義字符。?例如,searchPattern?字符串 "*t" 搜索?path?以字母 "t" 結尾的所有名稱。?searchPattern?字符串 "s*" 搜索?path?以字母 "s" 開頭的所有名稱。
詳情見??https://msdn.microsoft.com/zh-cn/library/ms143316(v=vs.110).aspx
3.獲取當前工程目錄
Environment.CurrentDirectory4.刪除指定目錄
Directory.Delete("D:\\code", true);5.創建指定目錄
Directory.CreateDirectory("D:\\code");6.查看當前路徑
Directory.GetCurrentDirectory()7.設置目錄屬性
DirectoryInfo NewDirInfo = new DirectoryInfo(@"c:\temp\NewDirectoty"); //設置目錄屬性未只讀、隱藏 NewDirInfo.Atttributes = FileAttributes.ReadOnly|FileAttributes.Hidden;8.移動目錄
Directory.Move(@"c:\temp\NewDirectory",@"c:\temp\Move");9.獲取指定目錄下的所有子目錄
string [] directorys = Directory.GetDirectories (@"c:\temp");2.文件操作 File類
1.判斷文件是否存在
File.Exists(string filePath)2.創建文件
public void CreateFile( string filePath ) {if (File.Exists(filePath)) return;//判斷文件是否存在FileStream fileStream = File.Create(filePath);if (fileStream != null)fileStream.Close();//關閉文件流 }3.刪除文件
File.Delete(string filePath);4.移動文件
File.Move(string path, string newPath);5.文件創建時間
File.GetCreationTime(string path);//獲取 File.SetCreationTime(string path, DateTime creationTime);//設置6.文件最后被寫入時間
File.GetLastWriteTime(string path);//獲取 SetLastWriteTime(string path, DateTime lastWriteTime);//設置7.文件上次被訪問的時間
File.GetLastAccessTime(string path);//獲取 File.SetLastAccessTime(string path, DateTime lastWriteTime);//設置8.打開文件
private void OpenFile() {FileStream textFile=File.Open(@"c:\temp\newFile.txt",FileMode.Append);byte [] Info = {(byte)'h',(byte)'e',(byte)'l',(byte)'l',(byte)'o'};textFile.Write(Info,0,Info.Length);textFile.Close(); }9.復制文件
File.Copy(@"c:\temp\newFile.txt",@"c:\temp\Copy.txt",true);10.設置文件屬性
//將c:\temp\newFile.txt文件設置為只讀、隱藏 File.SetAttributes(@"c:\temp\newFile.txt",FileAttributes.ReadOnly|FileAttributes.Hidden);11.讀取整個文件
string allStr = File.ReadAllText(filePath);3.路徑操作 Path類
Path類是靜態類,直接用類名調用以下方法即可
| string ChangeExtension(string path, string extension) | 更改路徑字符串的擴展名 |
| string Combine(params string[] paths) | 將字符串數組組合成一個路徑 |
| string Combine(string path1, string path2) | 將兩個字符串組合成一個路徑 |
| string GetDirectoryName(string path) | 返回指定路徑字符串的目錄信息 |
| string GetExtension(string path) | 返回指定路徑字符串的擴展名 |
| string GetFileName(string path) | 返回指定路徑字符串的文件名和擴展名 |
| string GetFileNameWithoutExtension(string path) | 返回不具有擴展名的指定路徑字符串的文件名 |
| string GetFullPath(string path) | 返回指定路徑字符串的絕對路徑 |
| char[] GetInvalidFileNameChars() | 獲取包含不允許在文件名中使用的字符的數組 |
| char[] GetInvalidPathChars() | 獲取包含不允許在路徑名中使用的字符的數組 |
| string GetPathRoot(string path) | 獲取指定路徑的根目錄信息 |
| string GetRandomFileName() | 返回隨機文件夾名或文件名 |
| string GetTempPath() | 返回當前用戶的臨時文件夾的路徑 |
| bool HasExtension(string path) | 返回路徑是否包含文件的擴展名 |
| bool IsPathRooted(string path) | 返回路徑字符串是否包含根 |
4.讀取文件?StreamReader類
1.StreamReader類的構造方法
| 構造方法 | 說明 |
| StreamReader(Stream stream) | 為指定的流創建 StreamReader 類的實例 |
| StreamReader(string path) | 為指定路徑的文件創建 StreamReader 類的實例 |
| StreamReader(Stream stream, Encoding encoding)? | 用指定的字符編碼為指定的流初始化 StreamReader 類的一個新實例 |
| StreamReader(string path, Encoding encoding) | 用指定的字符編碼為指定的文件名初始化? StreamReader 類的一個新實例 |
2.StreamReader類的屬性和方法
| Encoding CurrentEncoding | 只讀屬性,獲取當前流中使用的編碼方式 |
| bool EndOfStream | 只讀屬性,獲取當前的流位置是否在流結尾 |
| void Close() | 關閉流 |
| int Peek() | 獲取流中的下一個字符的整數,如果沒有獲取到字符, 則返回 -1 |
| int Read() | 獲取流中的下一個字符的整數 |
| int Read(char[] buffer, int index, int count) | 從指定的索引位置開始將來自當前流的指定的最多字符讀到緩沖區 |
| string ReadLine() | 從當前流中讀取一行字符并將數據作為字符串返回 |
| string ReadToEnd() | 讀取來自流的當前位置到結尾的所有字符 |
3.代碼示例
//定義文件路徑 string path = @"C:\temp\test.txt"; //創建 StreamReader 類的實例 StreamReader streamReader = new StreamReader(path); //判斷文件中是否有字符 while (streamReader.Peek() != -1) {//讀取文件中的一行字符string str = streamReader.ReadLine();Console.WriteLine(str); } streamReader.Close();5.寫入文件?StreamWriter類
1.StreamWriter類的構造方法
| StreamWriter(Stream stream)? | 為指定的流創建 StreamWriter 類的實例 |
| StreamWriter(string path) | 為指定路徑的文件創建 StreamWriter 類的實例 |
| StreamWriter(Stream stream, Encoding encoding) | 用指定的字符編碼為指定的流初始化 StreamWriter 類的一個新實例 |
| StreamWriter(string path, Encoding encoding) | 用指定的字符編碼為指定的文件名初始化 StreamWriter 類的一個新實例 |
2.StreamWriter類的屬性和方法
| bool AutoFlush | 屬性,獲取或設置是否自動刷新緩沖區 |
| Encoding Encoding | 只讀屬性,獲取當前流中的編碼方式 |
| void Close() | 關閉流 |
| void Flush() | 刷新緩沖區 |
| void Write(char value) | 將字符寫入流中 |
| void WriteLine(char value) | 將字符換行寫入流中 |
| Task WriteAsync(char value) | 將字符異步寫入流中 |
| Task WriteLineAsync(char value)? | 將字符異步換行寫入流中 |
3.代碼示例
string path = @"C:\temp\test.txt"; //創建StreamWriter 類的實例 StreamWriter streamWriter = new StreamWriter(path); //向文件中寫入姓名 streamWriter.WriteLine("小張"); //向文件中寫入手機號 streamWriter.WriteLine("13112345678"); //刷新緩存 streamWriter.Flush(); //關閉流 streamWriter.Close();二、動態鏈接庫kernel32
kernel32.dll是Windows9x/Me中非常重要的32位動態鏈接庫文件,屬于內核級文件。它控制著系統的內存管理、數據的輸入輸出操作和中斷處理,當Windows啟動時,kernel32.dll就駐留在內存中特定的寫保護區域,使別的程序無法占用這個內存區域。
1.寫入文件
/// <summary> /// 寫入文件 /// </summary> /// <param name="strSection">要寫入的段落名</param> /// <param name="strKey">要寫入的鍵</param> /// <param name="strValue">要寫入的值</param> /// <param name="strFilePath">INI文件的完整路徑和文件名</param> /// <returns></returns> [DllImport("kernel32")] private static extern long WritePrivateProfileString(string strSection, string strKey, string strValue, string strFilePath);/// <summary> /// 寫入字符串 /// </summary> public void WriteString(string strSection,string strKey,string strValue) {WritePrivateProfileString(strSection, strKey, strValue, m_filePath); } /// <summary> /// 寫整形 /// </summary> public void WriteInt(string strSection, string strKey, int intValue) {WriteString(strSection, strKey, intValue.ToString()); } /// <summary> /// 寫整形 /// </summary> public void WriteInt(string strSection, string strKey, long intValue) {WriteString(strSection, strKey, intValue.ToString()); } /// <summary> /// 寫bool /// </summary> public void WriteBool(string strSection, string strKey, bool value) {string str = value ? "true" : "false";WriteString(strSection, strKey, str); }2.讀取文件
/// <summary> /// 讀取文件 /// </summary> /// <param name="strSection">要讀取的段落名</param> /// <param name="strKey">要讀取的鍵</param> /// <param name="strDefine">讀取異常的情況下的默認值</param> /// <param name="retValue">key所對應的值,如果該key不存在則返回空值</param> /// <param name="nSize">值允許的大小</param> /// <param name="strFilePath">INI文件的完整路徑和文件名</param> /// <returns></returns> [DllImport("kernel32")] private static extern int GetPrivateProfileString(string strSection, string strKey, string strDefine, StringBuilder retValue, int nSize, string strFilePath);/// <summary> /// 讀取字符串 /// </summary> public string ReadString(string strSection, string strKey, string strDefine = "" ) {StringBuilder retValue = new StringBuilder(1024);int nSize = GetPrivateProfileString(strSection, strKey, strDefine, retValue, 1024, m_filePath);return retValue.ToString(); } /// <summary> /// 讀取int /// </summary> public int ReadInt(string strSection, string strKey, int intDefine = 0) {string str = ReadString(strSection, strKey, intDefine.ToString());int nValue = 0;int.TryParse(str, out nValue);return nValue; } /// <summary> /// 讀取bool /// </summary> public bool ReadBool(string strSection, string strKey, bool value = false) {string strv = value ? "true" : "false";string str = ReadString(strSection, strKey, strv );return str.Equals("true"); }?
總結
以上是生活随笔為你收集整理的C# 常用的文件IO操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php验证是否为整数(0、正整数、负整数
- 下一篇: 贪心法找钱python_python找钱