C#:讀寫簡單的文本文件

  C#:讀寫簡單的文本文件

常常我們會去讀寫一些簡單的文本文件,如:讀寫log文件等等。DotNet中對文件的處理比較簡單,但要注意的是:防止產生亂碼。
這裏,我將運用兩種方式來對文本文件進行讀寫。
一、一次性讀寫文件的全部內容
我們將要用到以下兩個類:FileInfo和FileStream,它們都位於System.IO命名空間中。
· FileInfo:通過此類可獲得指定文件的詳細內容,並且,還提供創建、複製、刪除、移動和打開文件的實例方法,除此,FileInfo還能通過其實例方法OpenRead()來創建FileStream對象。詳情可參考MSDN中的System.IO.FileInfo
· FileStream:支持同步和異步讀寫操作。使用FileStream類對文件進行讀取、寫入、打開和關閉等操作,並能對其他與文件相關的操作句柄進行操作。詳情可參考System.IO.FileStream
下面用一個簡單的Demo來演示:
1.導入必要的namespace;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;    // Import the namespace for using the FileInfo class and FileStream class
 
2.創建一個讀取文本文件的方法:ReadFile(string filename),並以byte[]型返回文本文件的所有內容;
static byte[] ReadFile(string filename)
{
       FileInfo fi 
= new FileInfo(filename);
       
      
// Using the OpenRead() method to create a FileStream instance     
       FileStream fs = fi.OpenRead();

       
byte[] bytes = new byte[fs.Length];

       
// Read content of the specified file, and store it with byte[] type
       fs.Read(bytes, 0, (int)fs.Length);

       
return bytes;        
}
 
1.創建一個將文本內容寫入指定文件的方法:WriteToFile(byte[] bytes, string filename);
static WriteToFile(byte[] bytes, string filename)
{
      FileStream fs; 
      
try
      
{
           
// Create a instance of FileStream with the specified filename
           fs = File.Create(filename);
           
// Write all the byte[] into the FileStream's instance
           fs.Write(bytes, 0, bytes.Length);
                
           
// Write content into the file    
           fs.Flush();  
      
           fs.Close();
       }

       
catch (Exception e)
       
{
            Console.WriteLine(e.ToString());
        }

}
 
4.現在我們只需在Main()方法中先後調用ReadFile和WriteToFile方法便可完成簡單的文本文件夾讀寫操作:
 
static void Main(string[] args)
{
      
string inputFile = @"d: estinput.txt";
      
string outputFile = @"d: estoutput.txt";
      WriteStrToFile(ReadFile(inputFile), outputFile);
}
 
需要注意:這種方式讀取文件其實是將文本文件中的內容以byte流的方式返回,再將這個byte流寫入到另一文件中,這樣有其好處:整讀整寫,也不需要考慮文件編碼,只要原輸入文件在操作系統中能正常顯示,那其輸出文件的顯示也不會有問題。
但是,有的時候,我們並不想去整讀一文檔,而可能只要讀取其中的某幾行,那以上的方式就對我們不大可行了。在此,我們給出第二種讀寫文件方式。
二、一次讀寫一行
我們將採用StreamReader類來讀取文本文件,還會用到與文件編碼相關的類Encoding,在寫文件時,仍然用FileStream。
· StreamReader: 繼承自System.IO.TextReader,能夠以一種特定的編碼從字節流中讀取字符。其默認編碼爲UTF-8,而並不是當前系統的ANSI。詳情請參見System.IO.StreamReader
· Encoding: 描述編碼。它用於對Unicode字符進行操作,而不是對任意二進制數據(如:字節數組)進行操作。請參考System.Text.Encoding
也用一Demo來簡單說明其用法:
1. 讀取指定文件中的一行內容,並以string類型返回;
 
static string ReadFile(string filename)
{
    
string content = "";

    
// Create a StreamReader by a specified Encoding type: Windows OS default type: ANSI
    StreamReader fileReader = new StreamReader(filename, Encoding.Default);

    
string tempStr;
    
while (true)
    
{
        tempStr 
= fileReader.ReadLine();
        
if (tempStr==null)
        
{
            
break;
        }

        content 
+= tempStr + " ";
    }


    
return content;
}
 
2.將一string類型的數據寫入指定的文件;
static void WriteToFile(string content, string filename)
{
    Encoding winDefault 
= Encoding.Default;
    FileStream fs;

    
try
{
    
// Create a instance of FileStream with the specified filename
        fs = File.Create(filename);
        
        
// Change the string data to byte[] data in the win default encoding: ANSI
        Byte[] bytes = winDefault.GetBytes(content);

        fs.Write(bytes, 
0, bytes.Length);
        fs.Flush();
        fs.Close(); 
    }

    
catch(Exception e)
    
{
        Console.WriteLine(e.ToString());
    }

}
 
3.在Main()方法中調用這兩個方法完成文件部分內容的讀寫;
static void Main(string[] args)
{
      
string inputFile = @"d: estinput.txt";
      
string outputFile = @"d: estoutput.txt"
      WriteStrToFile(ReadFile(inputFile), outputFile);
}
 
注意:在DotNet中,string數據永遠都是Unicode編碼形式,而正常情況下,Windows系統中的字符顯示編碼爲ANSI,要正確地從以ANSI編碼的文件中讀取數據並存放編碼爲Unicode的string類型,然後再將這Unicode編碼數據寫入文件並能在系統中正確顯示,就應該統一讀取和寫入時的編碼格式,以防顯示亂碼。因此,我們在讀取文件時(ReadFile()方法中),使用指定的Encoding.Default(即:ANSI)編碼方式讀取,再在寫入文件時(WriteToFile()方法中),使用Encoding.Default編碼將string類型數據轉換成byte流,這樣,我們就成功完成了編碼的統一,防止了亂碼的出現。
以上兩種方法簡單地描述了一下在DotNet中文本文件的讀寫,其關鍵在於字符的編碼。
我們再回過頭看方法一,這種方式不需要考慮編碼的原因在於:它在讀取文件時是以一種默認的編碼方式返回byte流,而在將此byte流寫入文件時也是以同樣的一種編碼,在這過程中並沒有編碼的轉換,因此,只要原數據文件顯示正常,則其寫入後的文件也必然會顯示正常。
而方法二有所不同,在讀寫過程中,出現幾次編碼的轉換:ANSI(原數據文件編碼)àUnicode(數據緩存中的編碼)àANSI(寫入後的數據編碼),爲了轉換成功,我們就必須統一讀寫過程中的編碼形式。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章