天天看點

檔案和檔案夾的操作——檔案流的使用

1、檔案的讀取和寫入

思路:主要用到了File類的CreateText方法和StreamWriter類的WriteLine方法。

(1)、File類的CreateText方法,該方法實作建立或打開一個檔案用于寫入UTF-8編碼的文本。文法如下:public static StreamWriter(string path)

(2)、StreamWriter類的WriteLine方法

該方法實作将後跟行結束符的字元串寫入檔案流,文法如下:

public virtual void WriteLine(string  value)

參數說明:value:要寫入的字元串,如果value為null,則僅寫入行結束字元。

檔案和檔案夾的操作——檔案流的使用

public partial class Form1 : Form

   {

       public Form1()

       {

           InitializeComponent();

       }

       private void button1_Click(object sender, EventArgs e)

           if (saveFileDialog1.ShowDialog() == DialogResult.OK)

           {

               textBox1.Text = saveFileDialog1.FileName;

           }

           else

               textBox1.Text = "";

       private void button2_Click(object sender, EventArgs e)

           if (String.IsNullOrEmpty(textBox1.Text.Trim()))//若檔案路徑為空

               MessageBox.Show("請設定檔案路徑!");

               return;

           if (String.IsNullOrEmpty(textBox2.Text.Trim()))//若文本内容為空

               MessageBox.Show("請輸入檔案内容!");

           if (!File.Exists(textBox1.Text))

           {//建立或打開一個檔案用于寫入 UTF-8 編碼的文本。

               using (StreamWriter sw = File.CreateText(textBox1.Text))                {

                   sw.WriteLine(textBox2.Text);//把字元串寫入文本流

                   MessageBox.Show("檔案建立成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

               }

               MessageBox.Show("該檔案已經存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

   }

2、OpenRead方法打開現有檔案并讀取

思路:主要用到了File類的OpenRead方法和FileStream類的Read方法。

(1)、File類的OpenRead方法,該方法實作打開現有檔案以進行讀取,文法格式如下:

public static FileStream OpenRead(string path)

參數說明:path:要打開以進行讀取的檔案。

傳回值:指定路徑上的隻讀檔案流。

(2)、FileStream類的Read方法

該方法實作從流中讀取位元組快并将該資料寫入給定的緩沖區中,文法如下:

public override int Read(byte[] array,int offset,int count)

Read方法中的參數說明:

參數

說明

Array

寫入資料的緩沖區

Offset

讀取的開始位置索引

Count

最多讀取的位元組數

傳回值

讀入Buffer中的總位元組數。如果目前的位元組數沒有所請求的那麼多,則總位元組數可能小于所請求的位元組數;或者如果已到達流的末尾,則為零。

例:

檔案和檔案夾的操作——檔案流的使用

private void button1_Click(object sender, EventArgs e)

           try

               openFileDialog1.Filter = "文本檔案(*.txt)|*.txt";//設定打開檔案的類型

               openFileDialog1.ShowDialog();

               textBox1.Text = openFileDialog1.FileName;//設定打開的檔案名稱

               FileStream fs = File.OpenRead(textBox1.Text);//打開現有檔案以進行讀取

               byte[] b = new byte[1024];//定義緩存

               while (fs.Read(b, 0, b.Length) > 0)//循環每次讀取1024個位元組到緩存中

               {//把位元組數組所有位元組轉為一個字元串

                   textBox2.Text = Encoding.Default.GetString(b);              

}

           catch { MessageBox.Show("請選擇檔案"); }

3、使用OpenWrite方法打開現有檔案并進行寫入

思路:是要用到了File類的OpenWrite方法,Encoding抽象類的GetBytes方法和FileStream類的Write方法,

File類的OpenWrite方法

該方法用于實作打開現有檔案以進行寫入,文法如下:

Public static FileStream OpenWrite(string path)

參數說明:path:要打開以盡心寫入的檔案。

傳回值:傳回具有寫入權限的指定路徑上的飛共享檔案流對象。

Encoding抽象類的GetBytes方法。該方法用于實作将指定的字元串中的所有字元編碼為一個位元組序列。文法如下:public virtual byte[] GetBytes(string s)

參數說明:s:包含要編碼的字元的字元串。

傳回值:傳回一個位元組數組,包含對指定的字元集進行編碼的結果。

FileStream類的Write方法。該方法實作使用從緩沖區讀取的資料将位元組塊寫入該流。文法如下:public override void Write(byte[] array,int offset,int count)

Write方法中的參數說明:

包含要寫入該流的資料的緩沖區

位置索引,從此處開始将位元組複制到目前流

要寫入目前流的最大位元組數。

無傳回值

 public partial class Form1 : Form {

public Form1()

{  InitializeComponent();}

           openFileDialog1.Filter = "文本檔案(*.txt)|*.txt";

           openFileDialog1.ShowDialog();

           textBox1.Text = openFileDialog1.FileName;

           if (String.IsNullOrEmpty(textBox1.Text.Trim()))

               MessageBox.Show("請設定檔案!");

               FileStream FStream = File.OpenWrite(textBox1.Text);

               Byte[] info = Encoding.Default.GetBytes(textBox2.Text);

               FStream.Write(info, 0, info.Length);

               FStream.Close();

               MessageBox.Show("寫入檔案成功!");

           catch (Exception ex)

               MessageBox.Show(ex.Message);

}

3、打開現有UTF-8編碼文本檔案并進行讀取

思路:主要用到File類的OpenText方法和StreamReader類的ReadToEnd方法,

File類的OpenText方法,該方法實作打開現有UTF-8編碼文本檔案以進行讀取。文法如下:public static StreamReader OpenText(string path)

(2)   StreamReader類的ReadToEnd()。參數說明:傳回值:傳回字元串形式的流的其餘部分(從目前位置到末尾)。如果目前位置位于流的末尾,則傳回空字元串(””)。

               openFileDialog1.Filter = "文本檔案(*.txt)|*.txt";

               textBox1.Text = openFileDialog1.FileName;

               StreamReader SReader = File.OpenText(textBox1.Text);

               textBox2.Text = SReader.ReadToEnd();

           catch { }

4、讀取檔案中的第一行資料

主要用到的方法:ReadLine();

openFileDialog1.Filter = "文本檔案(*.txt)|*.txt";

               StreamReader SReader = new StreamReader(textBox1.Text, Encoding.Default);

               textBox2.Text = SReader.ReadLine();

5、将文本檔案轉換成網頁檔案

思路:主要用到RichTextBox控件AppendText方法和SaveFile方法。

(1)、RichTextBox控件的AppendText方法,該方法實作向文本框的目前文本追加文本,格式如下:

Public void AppendText(string text)

SaveFile方法,該方法實作将RichTextBox中的内容儲存到特定類慈甯宮的檔案中,文法如下:public void Save File(string path,RichTextBoxStreamType fileType)

FileType: RichTextBoxStreamType枚舉之一,

枚舉值

RichText

RTF格式流

PlainText

用空格代替對象連接配接與嵌入(OLE)對象的純文字流

RichNoOleObjs

用空格代替OLE對象的豐富文本格式(RTF格式)流

TextTextOleObjs

具有OLE對象的文本表示形式的純文字流

UnicodePlainText

包含空格代替對象連結與嵌入(OLE)對象的文本流

 string strContent = "##科技有限公司是一家以計算機軟體技術為核心的高科技企業,多年來始終緻力于行業管理軟體開發、數字化出版物制作、計算機網絡系統綜合應用以及行業電子商務網站開發領域,涉及生産、管理、控制、倉儲、物流、營銷、服務等行業。公司擁有軟體開發和項目實施方面的資深專家和學習型技術團隊,多年來積累了豐富的技術文檔和學習資料,公司的開發團隊不僅是開拓進取的技術實踐者,更緻力于成為技術的普及和傳播者。";

               string strCompany = "##科技有限公司";

               string strWeb = "www.##soft.com";

               string strFileName = "公司網頁.htm";

               richTextBox1.Clear();

               richTextBox1.AppendText("<HTML>");

               richTextBox1.AppendText("<HEAD>");

               richTextBox1.AppendText("<TITLE>");

               richTextBox1.AppendText(strCompany);

               richTextBox1.AppendText("</TITLE>");

               richTextBox1.AppendText("</HEAD>");

               richTextBox1.AppendText("<BODY BGCOLOR='TAN'>");

               richTextBox1.AppendText("<CENTER>");

               richTextBox1.AppendText("<H2>" + strCompany + "</H2>");

               String strHyper = "<H4><A HREF='" + strWeb + "'>歡迎通路**科技公司網站:";

               richTextBox1.AppendText(strHyper + strWeb + "</A></H4>");

               richTextBox1.AppendText("</CENTER>");

               richTextBox1.AppendText(strContent);

               richTextBox1.AppendText("</BODY>");

               richTextBox1.AppendText("</HTML>");

               richTextBox1.SaveFile(strFileName, RichTextBoxStreamType.PlainText);

               System.Diagnostics.Process.Start(strFileName);

6、讀寫記憶體流資料

主要用到MemoryStream類的Capacity屬性,Write方法和Read方法。

檔案和檔案夾的操作——檔案流的使用

           byte[] BContent = Encoding.Default.GetBytes(textBox1.Text);

           MemoryStream MStream = new MemoryStream(100);

           MStream.Write(BContent, 0, BContent.Length);

           richTextBox1.Text = "配置設定給該流的位元組數:" + MStream.Capacity.ToString() + "\n流長度:"

               + MStream.Length.ToString() + "\n流的目前位置:" + MStream.Position.ToString();

           MStream.Seek(0, SeekOrigin.Begin);

           byte[] byteArray = new byte[MStream.Length];

           int count = MStream.Read(byteArray, 0, (int)MStream.Length - 1);

           while (count < MStream.Length)

               byteArray[count++] = Convert.ToByte(MStream.ReadByte());

           char[] charArray = new char[Encoding.Default.GetCharCount(byteArray, 0, count)];

           Encoding.Default.GetChars(byteArray, 0, count, charArray, 0);

           for (int i = 0; i < charArray.Length; i++)

               richTextBox2.Text += charArray[i].ToString();

6、建立并寫入二進制檔案資料

檔案和檔案夾的操作——檔案流的使用

思路:主要用到BinaryWriter類的構造方法和Write方法。

例: private void button2_Click(object sender, EventArgs e)

{

 if (String.IsNullOrEmpty(textBox1.Text.Trim()))

               MessageBox.Show("請選擇檔案路徑");

           if (String.IsNullOrEmpty(textBox2.Text.Trim()))

               MessageBox.Show("請設定檔案名稱");

               FileStream myStream = new FileStream(textBox1.Text + "\\" + textBox2.Text+".bin", FileMode.Create);

               BinaryWriter myWriter = new BinaryWriter(myStream);

               for (int i = 0; i < 10; i++)

               {

                   myWriter.Write(i);

               myWriter.Close();

               myStream.Close();

               MessageBox.Show("建立并寫入成功!");

           catch(Exception ex)

7、讀取二進制檔案的内容

 private void button1_Click(object sender, EventArgs e)

           openFileDialog1.Filter = "*.bin|*.bin";

               MessageBox.Show("請選擇檔案");

           textBox2.Text = string.Empty;

               FileStream myStream = new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read);

               BinaryReader myReader = new BinaryReader(myStream);

               for (int i = 0; i < myStream.Length; i++)

                   textBox2.Text += myReader.ReadInt32();

               myReader.Close();

檔案和檔案夾的操作——檔案流的使用

8、使用緩沖流複制檔案

思路:在使用緩沖流,需要用到System.IO命名空間下的BufferedStream類,BufferedStream流,也稱作緩沖流,它實作給另一個流上的讀寫操作添加一個緩沖層。緩沖流在記憶體中建立一個緩沖區,它會以最有效的增量從磁盤中讀取位元組到緩沖區,它會以最有效率的增量從磁盤中讀取位元組到緩沖區。緩沖區是記憶體中的位元組塊,用于緩存資料進而減少對作業系統的調用次數,緩沖區可提高讀取和寫入性能。

BufferedStream類的Read方法。該方法實作将位元組從目前緩沖流複制數組。格式如下:public override int Read(byte[] array,int offset,int count)

将位元組複制到緩沖區

位置索引,從此處開始讀取位元組

要讀取的位元組數

讀入array位元組數組中的總位元組數。如果可用的位元組沒有所請求的那麼多,總位元組數可能小于請求的位元組數;或者如果可讀取任何資料前就已達到流的末尾,則為零。

BufferedStream 類的Write方法。該方法實作位元組複制到緩沖流,并将緩沖流内的目前位置前進寫入的位元組數,文法如下:public override void Write(byte[] array,int offset,int count)。Write參數說明:

位元組數組,從該位元組數組count個位元組複制到目前緩沖流中。

緩沖區的偏移量,從此處開始将位元組複制到目前緩沖流中

要寫入目前緩沖流中的位元組數

BufferedStream類的Flush方法。該方法實作清楚該流的所有緩沖區,使得所有緩沖的資料都被寫入到基礎裝置。文法格式:public override void Flush()

注:由于緩沖流在記憶體的緩沖區中直接讀寫資料,而不是從硬碟中直接讀寫資料,是以它處理大容量的檔案尤為适合。

檔案和檔案夾的操作——檔案流的使用

 public partial class Form1 : Form

           openFileDialog1.Filter = "檔案(*.*)|*.*";

           folderBrowserDialog1.ShowDialog();

           textBox2.Text = folderBrowserDialog1.SelectedPath;

       private void button3_Click(object sender, EventArgs e)

               string str1 = textBox1.Text;

               string str2 = textBox2.Text + "\\" + textBox1.Text.Substring(textBox1.Text.LastIndexOf("\\") + 1, textBox1.Text.Length - textBox1.Text.LastIndexOf("\\") - 1);

               Stream myStream1, myStream2;

               BufferedStream myBStream1, myBStream2;

               byte[] myByte = new byte[1024];

               int i;

               myStream1 = File.OpenRead(str1);

               myStream2 = File.OpenWrite(str2);

               myBStream1 = new BufferedStream(myStream1);

               myBStream2 = new BufferedStream(myStream2);

               i = myBStream1.Read(myByte, 0, 1024);

               while (i > 0)

                   myBStream2.Write(myByte, 0, i);

                   i = myBStream1.Read(myByte, 0, 1024);

               myBStream2.Flush();

               myStream1.Close();

               myBStream2.Close();

               MessageBox.Show("檔案複制完成");

9、如何使用GzipStream壓縮檔案?

GzipStream類位于System.IO.Compression命名空間下,提供用于壓縮和解壓縮流的方法和屬性。該類表示GZip資料格式,這種格式包括一個檢測資料損壞的循環備援校驗值。當使用GzipStream類構造一個壓縮流後,就可以使用該類的Write方法寫資料,進而實作壓縮功能。

Write方法實作從指定的位元組數組中将要壓縮的位元組寫入基礎流。文法如下:

Public override void Write(byte[] array,int offset, int count)

參數說明:(1)array 用于存儲要壓縮位元組的數組。(2)offset 數組中開始讀取的位置(2)count 壓縮的位元組數。

檔案和檔案夾的操作——檔案流的使用

using System.IO.Compression;

namespace GZipFile

{

   public partial class Form1 : Form

           openFileDialog1.Filter = "所有檔案(*.*)|*.*";

           if (openFileDialog1.ShowDialog() == DialogResult.OK)

           if (String.IsNullOrEmpty(textBox1.Text))

               MessageBox.Show("請選擇源檔案!", "資訊提示");

           if (String.IsNullOrEmpty(textBox2.Text))

               MessageBox.Show("請輸入壓縮檔案名!", "資訊提示");

           string str1 = textBox1.Text;

           string str2 = textBox2.Text.Trim();

           byte[] myByte = null;

           FileStream myStream = null;

           FileStream myDesStream = null;

           GZipStream myComStream = null;

               myStream = new FileStream(str1, FileMode.Open, FileAccess.Read, FileShare.Read);

               myByte = new byte[myStream.Length];

               myStream.Read(myByte, 0, myByte.Length);

               myDesStream = new FileStream(str2, FileMode.OpenOrCreate, FileAccess.Write);

               myComStream = new GZipStream(myDesStream, CompressionMode.Compress, true);

               myComStream.Write(myByte, 0, myByte.Length);

               MessageBox.Show("壓縮檔案完成!");

           finally

               myComStream.Close();

               myDesStream.Close();

10、如何使用Gzip解壓檔案

思路:使用GzipStream類的Read方法讀取資料,進而實作解壓縮。文法如下:

Public override int Read(byte[] array,int offset,int count)。

參數說明:(1)array 用于存儲壓縮的位元組的數組。(2)offset 數組中開始讀取的位置(3)count 解壓縮的位元組數。(4)傳回值 解壓縮到位元組數組中的位元組數。如果已到達流的末尾,則傳回0或讀取的位元組數

檔案和檔案夾的操作——檔案流的使用

namespace UnGzipFile

           openFileDialog1.Filter = "壓縮檔案(*.gzip)|*.gzip";

               MessageBox.Show("請選擇GZIP檔案!", "資訊提示");

               MessageBox.Show("請輸入解壓檔案名!", "資訊提示");

           GZipStream myDeComStream = null;

               myStream = new FileStream(str1, FileMode.Open);

               myDeComStream = new GZipStream(myStream, CompressionMode.Decompress, true);

               myByte = new byte[4];

               int myPosition = (int)myStream.Length - 4;

               myStream.Position = myPosition;

               myStream.Read(myByte, 0, 4);

               myStream.Position = 0;

               int myLength = BitConverter.ToInt32(myByte, 0);

               byte[] myData = new byte[myLength + 100];

               int myOffset = 0;

               int myTotal = 0;

               while (true)

                   int myBytesRead = myDeComStream.Read(myData, myOffset, 100);

                   if (myBytesRead == 0)

                       break;

                   myOffset += myBytesRead;

                   myTotal += myBytesRead;

               myDesStream = new FileStream(str2, FileMode.Create);

               myDesStream.Write(myData, 0, myTotal);

               myDesStream.Flush();

               MessageBox.Show("解壓檔案完成!");

               myDeComStream.Close();

11、調用WinRAR實作檔案的壓縮和解壓

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Diagnostics;

using System.IO;

public partial class Zip : System.Web.UI.Page

{

   protected void Page_Load(object sender, EventArgs e)

   {

   }

   //壓縮檔案

   protected void Button1_Click(object sender, EventArgs e)

       ProcessStartInfo startinfo = new ProcessStartInfo(); ;

       Process process = new Process();

       string rarName = "1.rar"; //壓縮後檔案名

       string path = @"C:\images"; //待壓縮打封包件夾

       string rarPath = @"C:\zip";  //壓縮後存放檔案夾

       string rarexe = @"c:\Program Files\WinRAR\WinRAR.exe";  //WinRAR安裝位置

       try

       {

           //壓縮指令,相當于在要壓縮的檔案夾(path)上點右鍵->WinRAR->添加到壓縮檔案->輸入壓縮檔案名(rarName)

           string cmd = string.Format("a {0} {1} -r",

                               rarName,

                               path);

           startinfo.FileName = rarexe;

           startinfo.Arguments = cmd;                          //設定指令參數

           startinfo.WindowStyle = ProcessWindowStyle.Hidden;  //隐藏 WinRAR 視窗

           startinfo.WorkingDirectory = rarPath;

           process.StartInfo = startinfo;

           process.Start();

           process.WaitForExit(); //無限期等待程序 winrar.exe 退出

           if (process.HasExited)

           {

               MSCL.JsHelper.Alert("壓縮成功!", Page);

           }

       }

       catch (Exception ex)

           MSCL.JsHelper.Alert(ex.Message, Page);

       finally

           process.Dispose();

           process.Close();

       }        

   //解壓檔案

   protected void Button2_Click(object sender, EventArgs e)

       string rarName = "1.rar"; //将要解壓縮的 .rar 檔案名(包括字尾)

       string path = @"C:\images1"; //檔案解壓路徑(絕對)

       string rarPath = @"C:\zip";  //将要解壓縮的 .rar 檔案的存放目錄(絕對路徑)

           //解壓縮指令,相當于在要壓縮檔案(rarName)上點右鍵->WinRAR->解壓到目前檔案夾

           string cmd = string.Format("x {0} {1} -y",

               MSCL.JsHelper.Alert("解壓縮成功!", Page);

       }