文件和文件夹的操作——文件流的使用

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("请输入文件内容!");

                return;

            }

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

            {//创建或打开一个文件用于写入 UTF-8 编码的文本。

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

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

                    MessageBox.Show("文件创建成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }

            }

            else

            {

                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方法,

  1. File类的OpenWrite方法

该方法用于实现打开现有文件以进行写入,语法如下:

Public static FileStream OpenWrite(string path)

参数说明:path:要打开以尽心写入的文件。

返回值:返回具有写入权限的指定路径上的飞共享文件流对象。

  1. Encoding抽象类的GetBytes方法。该方法用于实现将指定的字符串中的所有字符编码为一个字节序列。语法如下:public virtual byte[] GetBytes(string s)

参数说明:s:包含要编码的字符的字符串。

返回值:返回一个字节数组,包含对指定的字符集进行编码的结果。

  1. FileStream类的Write方法。该方法实现使用从缓冲区读取的数据将字节块写入该流。语法如下:public override void Write(byte[] array,int offset,int count)

Write方法中的参数说明:

参数

说明

Array

包含要写入该流的数据的缓冲区

Offset

位置索引,从此处开始将字节复制到当前流

Count

要写入当前流的最大字节数。

返回值

无返回值

例:

  public partial class Form1 : Form {

public Form1()

{  InitializeComponent();}

        private void button1_Click(object sender, EventArgs e)

        {

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

            openFileDialog1.ShowDialog();

            textBox1.Text = openFileDialog1.FileName;

        }

        private void button2_Click(object sender, EventArgs e)

        {

          

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

            {

                MessageBox.Show("请设置文件!");

                return;

            }

            try

            {

                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方法,

  1. File类的OpenText方法,该方法实现打开现有UTF-8编码文本文件以进行读取。语法如下:public static StreamReader OpenText(string path)

(2)   StreamReader类的ReadToEnd()。参数说明:返回值:返回字符串形式的流的其余部分(从当前位置到末尾)。如果当前位置位于流的末尾,则返回空字符串(””)。

例:

private void button1_Click(object sender, EventArgs e)

        {

            try

            {

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

                openFileDialog1.ShowDialog();

                textBox1.Text = openFileDialog1.FileName;

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

                textBox2.Text = SReader.ReadToEnd();

            }

            catch { }

        }

4、读取文件中的第一行数据

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

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

                openFileDialog1.ShowDialog();

                textBox1.Text = openFileDialog1.FileName;

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

                textBox2.Text = SReader.ReadLine();

5、将文本文件转换成网页文件

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

(1)、RichTextBox控件的AppendText方法,该方法实现向文本框的当前文本追加文本,格式如下:

Public void AppendText(string text)

  1. 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方法。

例:

private void button1_Click(object sender, EventArgs e)

        {

            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("请选择文件路径");

                return;

            }

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

            {

                MessageBox.Show("请设置文件名称");

                return;

            }

            try

            {

                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)

            {

                MessageBox.Show(ex.Message);

            }

        }

7、读取二进制文件的内容

例:

  private void button1_Click(object sender, EventArgs e)

        {

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

            openFileDialog1.ShowDialog();

            textBox1.Text = openFileDialog1.FileName;

        }

        private void button2_Click(object sender, EventArgs e)

        {

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

            {

                MessageBox.Show("请选择文件");

                return;

            }

            textBox2.Text = string.Empty;

            try

            {

                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();

                myStream.Close();

            }

            catch { }

        }

8、使用缓冲流复制文件

思路:在使用缓冲流,需要用到System.IO命名空间下的BufferedStream类,BufferedStream流,也称作缓冲流,它实现给另一个流上的读写操作添加一个缓冲层。缓冲流在内存中创建一个缓冲区,它会以最有效的增量从磁盘中读取字节到缓冲区,它会以最有效率的增量从磁盘中读取字节到缓冲区。缓冲区是内存中的字节块,用于缓存数据从而减少对操作系统的调用次数,缓冲区可提高读取和写入性能。

  1. BufferedStream类的Read方法。该方法实现将字节从当前缓冲流复制数组。格式如下:public override int Read(byte[] array,int offset,int count)

参数

说明

Array

将字节复制到缓冲区

Offset

位置索引,从此处开始读取字节

Count

要读取的字节数

返回值

读入array字节数组中的总字节数。如果可用的字节没有所请求的那么多,总字节数可能小于请求的字节数;或者如果可读取任何数据前就已达到流的末尾,则为零。

  1. BufferedStream 类的Write方法。该方法实现字节复制到缓冲流,并将缓冲流内的当前位置前进写入的字节数,语法如下:public override void Write(byte[] array,int offset,int count)。Write参数说明:

参数

说明

Array

字节数组,从该字节数组count个字节复制到当前缓冲流中。

Offset

缓冲区的偏移量,从此处开始将字节复制到当前缓冲流中

Count

要写入当前缓冲流中的字节数

返回值

无返回值

  1. BufferedStream类的Flush方法。该方法实现清楚该流的所有缓冲区,使得所有缓冲的数据都被写入到基础设备。语法格式:public override void Flush()

注:由于缓冲流在内存的缓冲区中直接读写数据,而不是从硬盘中直接读写数据,所以它处理大容量的文件尤为适合。

例:

   public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

            openFileDialog1.Filter = "文件(*.*)|*.*";

            openFileDialog1.ShowDialog();

            textBox1.Text = openFileDialog1.FileName;

        }

        private void button2_Click(object sender, EventArgs e)

        {

            folderBrowserDialog1.ShowDialog();

            textBox2.Text = folderBrowserDialog1.SelectedPath;

        }

        private void button3_Click(object sender, EventArgs e)

        {

            try

            {

                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("文件复制完成");

            }

            catch(Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

}

9、如何使用GzipStream压缩文件?

GzipStream类位于System.IO.Compression命名空间下,提供用于压缩和解压缩流的方法和属性。该类表示GZip数据格式,这种格式包括一个检测数据损坏的循环冗余校验值。当使用GzipStream类构造一个压缩流后,就可以使用该类的Write方法写数据,从而实现压缩功能。

  1. 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

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

            openFileDialog1.Filter = "所有文件(*.*)|*.*";

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

            {

                textBox1.Text = openFileDialog1.FileName;

            }

        }

        private void button2_Click(object sender, EventArgs e)

        {

            if (String.IsNullOrEmpty(textBox1.Text))

            {

                MessageBox.Show("请选择源文件!", "信息提示");

                return;

            }

            if (String.IsNullOrEmpty(textBox2.Text))

            {

                MessageBox.Show("请输入压缩文件名!", "信息提示");

                return;

            }

            string str1 = textBox1.Text;

            string str2 = textBox2.Text.Trim();

            byte[] myByte = null;

            FileStream myStream = null;

            FileStream myDesStream = null;

            GZipStream myComStream = null;

            try

            {

                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("压缩文件完成!");

            }

            catch { }

            finally

            {

                myStream.Close();

                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或读取的字节数

using System.IO.Compression;

namespace UnGzipFile

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

            openFileDialog1.Filter = "压缩文件(*.gzip)|*.gzip";

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

            {

                textBox1.Text = openFileDialog1.FileName;

            }

        }

        private void button2_Click(object sender, EventArgs e)

        {

            if (String.IsNullOrEmpty(textBox1.Text))

            {

                MessageBox.Show("请选择GZIP文件!", "信息提示");

                return;

            }

            if (String.IsNullOrEmpty(textBox2.Text))

            {

                MessageBox.Show("请输入解压文件名!", "信息提示");

                return;

            }

            string str1 = textBox1.Text;

            string str2 = textBox2.Text.Trim();

            byte[] myByte = null;

            FileStream myStream = null;

            FileStream myDesStream = null;

            GZipStream myDeComStream = null;

            try

            {

                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("解压文件完成!");

            }

            catch { }

            finally

            {

                myStream.Close();

                myDeComStream.Close();

                myDesStream.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) 

    { 

        ProcessStartInfo startinfo = new ProcessStartInfo(); ; 

        Process process = new Process(); 

        string rarName = "1.rar"; //将要解压缩的 .rar 文件名(包括后缀) 

        string path = @"C:\images1"; //文件解压路径(绝对) 

        string rarPath = @"C:\zip";  //将要解压缩的 .rar 文件的存放目录(绝对路径) 

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

        try 

        { 

            //解压缩命令,相当于在要压缩文件(rarName)上点右键->WinRAR->解压到当前文件夹 

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

                                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(); 

        }    

    } 

}

发布了60 篇原创文章 · 获赞 7 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/hhhhhhhhhhwwwwwwwwww/article/details/105593664