C#讀寫檔案的方法匯總

來源:互聯網
上載者:User

1、使用FileStream讀寫檔案

檔案頭:

複製代碼 代碼如下:using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

讀檔案核心代碼:

複製代碼 代碼如下:byte[] byData = new byte[100];
char[] charData = new char[1000];
try
{
FileStream sFile = new FileStream("檔案路徑",FileMode.Open);
sFile.Seek(55, SeekOrigin.Begin);
sFile.Read(byData, 0, 100); //第一個參數是被傳進來的位元組數組,用以接受FileStream對象中的資料,第2個參數是位元組數組中開始寫入資料的位置,它通常是0,表示從數組的開端檔案中向數組寫資料,最後一個參數規定從檔案讀多少字元.
}
catch (IOException e)
{
Console.WriteLine("An IO exception has been thrown!");
Console.WriteLine(e.ToString());
Console.ReadLine();
return;
}
Decoder d = Encoding.UTF8.GetDecoder();
d.GetChars(byData, 0, byData.Length, charData, 0);
Console.WriteLine(charData);
Console.ReadLine();

寫檔案核心代碼:

複製代碼 代碼如下:FileStream fs = new FileStream(檔案路徑,FileMode.Create);
//獲得位元組數組
byte [] data =new UTF8Encoding().GetBytes(String);
//開始寫入
fs.Write(data,0,data.Length);
//清空緩衝區、關閉流
fs.Flush();
fs.Close();

2、使用StreamReader和StreamWriter

檔案頭:

複製代碼 代碼如下:using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

StreamReader讀取檔案:

複製代碼 代碼如下:StreamReader objReader = new StreamReader(檔案路徑);
string sLine="";
ArrayList LineList = new ArrayList();
while (sLine != null)
{
sLine = objReader.ReadLine();
if (sLine != null&&!sLine.Equals(""))
LineList.Add(sLine);
}
objReader.Close();
return LineList;

StreamWriter寫檔案:

複製代碼 代碼如下:FileStream fs = new FileStream(檔案路徑, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//開始寫入
sw.Write(String);
//清空緩衝區
sw.Flush();
//關閉流
sw.Close();
fs.Close();

方式一:用FileStream

複製代碼 代碼如下://執行個體化一個儲存檔案對話方塊
SaveFileDialog sf = new SaveFileDialog();
//設定檔案檔案類型
sf.Filter = "txt檔案|*.txt|所有檔案|*.*";
//如果使用者沒有輸入副檔名,自動追加尾碼
sf.AddExtension = true;
//設定標題
sf.Title = "寫檔案";
//如果使用者點擊了儲存按鈕
if(sf.ShowDialog()==DialogResult.OK)
{
//執行個體化一個檔案流--->與寫入檔案相關聯
FileStream fs = new FileStream(sf.FileName,FileMode.Create);
//獲得位元組數組
byte [] data =new UTF8Encoding().GetBytes(this.textBox1.Text);
//開始寫入
fs.Write(data,0,data.Length);
//清空緩衝區、關閉流
fs.Flush();
fs.Close();
}

方式二:用StreamWriter

複製代碼 代碼如下://執行個體化一個儲存檔案對話方塊
SaveFileDialog sf = new SaveFileDialog();
//設定檔案檔案類型
sf.Filter = "txt檔案|*.txt|所有檔案|*.*";
//如果使用者沒有輸入副檔名,自動追加尾碼
sf.AddExtension = true;
//設定標題
sf.Title = "寫檔案";
//如果使用者點擊了儲存按鈕
if (sf.ShowDialog() == DialogResult.OK)
{
//執行個體化一個檔案流--->與寫入檔案相關聯
FileStream fs = new FileStream(sf.FileName, FileMode.Create);
//執行個體化一個StreamWriter-->與fs相關聯
StreamWriter sw = new StreamWriter(fs);
//開始寫入
sw.Write(this.textBox1.Text);
//清空緩衝區
sw.Flush();
//關閉流
sw.Close();
fs.Close();
}
string FileName = Guid.NewGuid().ToString() + ".txt"; //GUID產生唯一檔案名
StringBuilder ckpw = new StringBuilder("\"憑證輸出\", \"V800\", \"001\", \"東風隨州專用汽車有限公司\"," + "\"F89自由項16\", \"F90審核日期:\"");
if (!FileIO.IsFolderExists(Server.MapPath("pzsc")))
FileIO.CreaterFolder(Server.MapPath(""), "file://pzsc/");
string filePath = Server.MapPath("pzsc") + "\\" + FileName;
System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, false, Encoding.GetEncoding("GB2312"));//建立的時候需要指定編碼格式,預設是UTF-8,中文顯示亂碼
sw.WriteLine(ckpw.ToString());
sw.Close();

方式三:用BinaryWriter

複製代碼 代碼如下://執行個體化一個儲存檔案對話方塊
SaveFileDialog sf = new SaveFileDialog();
//設定檔案檔案類型
sf.Filter = "txt檔案|*.txt|所有檔案|*.*";
//如果使用者沒有輸入副檔名,自動追加尾碼
sf.AddExtension = true;
//設定標題
sf.Title = "寫檔案";
//如果使用者點擊了儲存按鈕
if (sf.ShowDialog() == DialogResult.OK)
{
//執行個體化一個檔案流--->與寫入檔案相關聯
FileStream fs = new FileStream(sf.FileName, FileMode.Create);
//執行個體化BinaryWriter
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(this.textBox1.Text);
//清空緩衝區
bw.Flush();
//關閉流
bw.Close();
fs.Close();
}

C#緩衝流樣本------>用緩衝流複製檔案

C#檔案處理操作必須先匯入命名空間:using System.IO;

背景:使用VS2005、一個按鈕、一個表單、C#緩衝流、把D:\KuGoo\愛得太多.wma複製到D:\並更名為love.wma,即:D:\love.wma

在按鈕的Click事件中添加如下代碼:

複製代碼 代碼如下:private void button1_Click(object sender, EventArgs e)
{
//建立兩個檔案流 一個是源檔案相關,另一個是要寫入的檔案
FileStream fs = new FileStream(@"D:\KuGoo\愛得太多.wma",FileMode.Open);
FileStream fs2 = new FileStream(@"D:\love.wma",FileMode.Create);
//建立一個位元組數組,作為兩者之間的媒介
//好比兩個人拿蘋果,這個位元組數組就好比一個籃子,一個人作死的把蘋果送到籃子裡面,
//而我就可以作死得拿蘋果,通過這個媒介我們互不干擾,
//不需要互相等待【她往籃子裡面放了蘋果我才可以去拿】,提高了效率
byte[] data = new byte[1024];
//建立兩個緩衝流,與兩個檔案流相關聯
BufferedStream bs = new BufferedStream(fs);
BufferedStream bs2= new BufferedStream(fs2);
//fs作死的讀,fs2作死的寫,直到fs沒有位元組可讀fs2就不寫了
//好比,一個人作死的往籃子裡面丟蘋果,另一個人作死得往籃子裡面拿蘋果,直到籃子裡面沒有蘋果拿了為止
//即-->那個人沒有蘋果往籃子裡面放了
while(fs.Read(data,0,data.Length)>0)
{
fs2.Write(data,0,data.Length);
fs2.Flush();
}
//關閉流,好比兩個人累了,都要休息 呵呵o(∩_∩)o...
fs.Close();
fs2.Close();
}

C#記憶體流樣本----->用記憶體流來讀取圖片
C#檔案處理操作必須先匯入命名空間:using System.IO;

背景:一個表單、一個pictureBox、一個lable[沒有選擇圖片,lable的text為"圖片未選擇"],在pictureBox1的Click事件中添加如下代碼:

複製代碼 代碼如下:private void pictureBox1_Click(object sender, EventArgs e)
{
//執行個體化一個開啟檔案對話方塊
OpenFileDialog op = new OpenFileDialog();
//設定檔案的類型
op.Filter = "JPG圖片|*.jpg|GIF圖片|*.gif";
//如果使用者點擊了開啟按鈕、選擇了正確的圖片路徑則進行如下操作:
if(op.ShowDialog()==DialogResult.OK)
{
//清空文本
this.label1.Text = "";
//執行個體化一個檔案流
FileStream fs = new FileStream(op.FileName, FileMode.Open);
//把檔案讀取到位元組數組
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
fs.Close();
//執行個體化一個記憶體流--->把從檔案流中讀取的內容[位元組數組]放到記憶體流中去
MemoryStream ms = new MemoryStream(data);
//設定圖片框 pictureBox1中的圖片
this.pictureBox1.Image = Image.FromStream(ms);
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.