以字节形式向磁盘写入数据通常称为字节流(比特流)
常常使用System.Io
常用的类
|
类
|
说明
|
|
File
|
提供用于创建、复制、删除、移动和打开文件的静态方法,并协助创建 FileStream 对象。
|
|
FileInfo
|
提供创建、复制、删除、移动和打开文件的实例方法,并且帮助创建 FileStream 对象。无法继承此类。
|
|
FileStream
|
公开以文件为主的 Stream,既支持同步读写操作,也支持异步读写操作。
|
|
BinaryReader
|
用特定的编码将基元数据类型读作二进制值。
|
|
BinaryWriter
|
以二进制形式将基元类型写入流,并支持用特定的编码写入字符串。
|
|
BufferedStream
|
给另一流上的读写操作添加一个缓冲层。无法继承此类。
|
|
Directory
|
公开用于创建、移动和枚举通过目录和子目录的静态方法。无法继承此类。
|
|
DirectoryInfo
|
公开用于创建、移动和枚举目录和子目录的实例方法。无法继承此类。
|
|
Path
|
对包含文件或目录路径信息的 String 实例执行操作。这些操作是以跨平台的方式执行的。
|
|
StreamReader
|
实现一个 TextReader,使其以一种特定的编码从字节流中读取字符。
|
|
StreamWriter
|
实现一个 TextWriter,使其以一种特定的编码向流中写入字符。
|
|
FileSysWatcher
|
侦听文件系统更改通知,并在目录或目录中的文件发生更改时引发事件。
|
基本使用类的介绍
1.1File
常用方法
类File提供用于创建、复制、删除、移动和打开文件的静态方法
|
方法
|
说明
|
|
Move
|
将指定文件移到新位置,并提供指定新文件名的选项。
|
|
Delete
|
删除指定的文件。如果指定的文件不存在,则不引发异常。
|
|
Copy
|
已重载。 将现有文件复制到新文件。
|
|
CreateText
|
创建或打开一个文件用于写入 UTF-8 编码的文本。
|
|
OpenText
|
打开现有 UTF-8 编码文本文件以进行读取。
|
|
Open
|
已重载。 打开指定路径上的 FileStream。
|
eg

1 using System;
2 using System.IO;
3 class Test
4 {
5 public static void Main()
6 {
7 string path = @"c:\temp\123.txt";
8 if (!File.Exists(path))
9 {
10 // 创建文件以便写入内容。
11 using (StreamWriter sw = File.CreateText(path))
12 {
13 sw.WriteLine("Hello");
14 sw.WriteLine("And");
15 sw.WriteLine("Welcome");
16 }
17 }
18 // 打开文件从里面读数据。
19 using (StreamReader sr = File.OpenText(path))
20 {
21 string s = "";
22 while ((s = sr.ReadLine()) != null)
23 {
24 Console.WriteLine(s);
25 }
26 }
27 try
28 {
29 string path2 = path + "temp";
30 // 确认将要拷贝成的文件是否已经有同名的文件存在。
31 File.Delete(path2);
32 // 拷贝文件。
33 File.Copy(path, path2);
34 Console.WriteLine("{0} was copied to {1}.", path, path2);
35 // 删除新生成的文件。
36 File.Delete(path2);
37 Console.WriteLine("{0} was successfully deleted.", path2);
38 }
39 catch (Exception e)
40 {
41 Console.WriteLine("The process failed: {0}", e.ToString());
42 }
43 }
44 }
1.2FileInfo
类FileInfo提供创建、复制、删除、移动和打开文件的实例方法,并且帮助创建 FileStream 对象。无法继承此类
|
属性
|
说明
|
|
Attributes
|
获取或设置当前 FileSystemInfo 的 FileAttributes。(从 FileSystemInfo 继承。)
|
|
CreationTime
|
获取或设置当前 FileSystemInfo 对象的创建时间。(从 FileSystemInfo 继承。)
|
|
Directory
|
获取父目录的实例。
|
|
DirectoryName
|
获取表示目录的完整路径的字符串。
|
|
Exists
|
已重写。获取指示文件是否存在的值。
|
|
Extension
|
获取表示文件扩展名部分的字符串。(从 FileSystemInfo 继承。)
|
获取目录名

1 using System;
2 using System.IO;
3 class Test
4 {
5 public static void Main()
6 {
7 string fileName = "C:\\autoexec.bat";
8 FileInfo fileInfo = new FileInfo(fileName);
9 if (!fileInfo.Exists)
10 {
11 return;
12 }
13 Console.WriteLine("{0} has a directoryName of {1}",fileName,fileInfo.DirectoryName);
14 /* 下面是代码的处理结果,
15 * 实际的结果因机器不同:
16 *
17 * C:\autoexec.bat has a directoryName of C:\
18 */
19 }
20 }
同磁盘下文件复制问题:

1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Text;
7 using System.Windows.Forms;
8 using System.IO;
9 namespace FileOptionApplication
10 {
11 public partial class Form1 : Form
12 {
13 public Form1()
14 {
15 InitializeComponent();
16 }
17 /// <summary>
18 /// 复制文本文件
19 /// </summary>
20 private void button1_Click(object sender, EventArgs e)
21 {
22 string somefile = @"C:\Documents and Settings\Administrator\My Documents\SQL Server2000安装故障.txt";
23 string target = @"c:\2.txt";
24 if (!File.Exists(somefile))
25 {
26 MessageBox.Show("文件不存在!");
27 }
28 else
29 {
30 if (File.Exists(target))
31 {
32 File.Delete(target);
33 }
34 File.Copy(somefile, target);
35 MessageBox.Show("文件复制成功!");
36 }
37 }
38 /// <summary>
39 /// 创建文本文件
40 /// </summary>
41 private void button2_Click(object sender, EventArgs e)
42 {
43 string target = @"c:\2.txt";
44 if (File.Exists(target))
45 {
46 File.Delete(target);
47 }
48 File.CreateText(target);
49 }
50 /// <summary>
51 /// 删除文本文件
52 /// </summary>
53 private void button3_Click(object sender, EventArgs e)
54 {
55 string target = @"c:\2.txt";
56 if (File.Exists(target))
57 {
58 File.Delete(target);
59 MessageBox.Show("文件删除成功!");
60 }
61 }
62 }
63 }
64
65 ------------------通过FileInfo类执行同样的复制
66
67 private void button1_Click(object sender, EventArgs e)
68 {
69 string path = @"C:\WINDOWS\IE4 Error Log.txt";
70 string target = @"c:\1.txt";
71 FileInfo myfile = new FileInfo(path);
72 if (!myfile.Exists)
73 {
74 MessageBox.Show("对不起,未发现路径文件!");
75 }
76 else
77 {
78 myfile.CopyTo(target);
79 MessageBox.Show("复制成功!");
80 }
81 }
获取文件的基本信息
向一个Form窗体上拖拽三个Lable控件和一个Button控件,Button控件的text属性设置为“获取文件信息”

代码

1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Text;
7 using System.Windows.Forms;
8 using System.IO;
9
10 namespace FileOptionApplication
11 {
12 public partial class Form2 : Form
13 {
14 public Form2()
15 {
16 InitializeComponent();
17 }
18 /// <summary>
19 /// 获取文件信息单击事件
20 /// </summary>
21 private void button1_Click(object sender, EventArgs e)
22 {
23 string somefile = @"C:\Documents and Settings\Administrator\My Documents\SQL Server2000安装故障.txt";
24 FileInfo myfile = new FileInfo(somefile);
25 if (myfile.Exists)
26 {
27 MessageBox.Show("文件已经存在");
28 label1.Text = "文件创建时间:" + myfile.CreationTime.ToString();
29 label2.Text = "文件夹:" + myfile.Directory.ToString();
30 label3.Text = "文件夹名称:" + myfile.DirectoryName.ToString() + ",文件扩展名:" + myfile.Extension.ToString();
31 }
32 else
33 {
34 MessageBox.Show("文件并不存在");
35 }
36 }
37 }
38 }
1.3 Directory公开用于创建、移动和枚举通过目录和子目录的静态方法
常用的方法
|
方法
|
说明
|
|
Move
|
将文件或目录及其内容移到新位置。
|
|
Delete
|
已重载。 删除指定的目录。
|
|
CreateDirectory
|
已重载。 创建指定路径中的所有目录
|
|
GetCreationTime
|
获取目录的创建日期和时间。
|
|
GetCurrentDirectory
|
获取应用程序的当前工作目录。
|
|
GetFiles
|
已重载。 返回指定目录中的文件的名称
|
目录创建了多少天

1 using System;
2 using System.IO;
3
4 class Test
5 {
6 public static void Main()
7 {
8 try
9 {
10 // 获取当前目录的创建时间.
11 DateTime dt = Directory.GetCreationTime(Environment.CurrentDirectory);
12 // 给用户反馈信息.
13 if (DateTime.Now.Subtract(dt).TotalDays > 364)
14 {
15 Console.WriteLine("This directory is over a year old.");
16 }
17 else if (DateTime.Now.Subtract(dt).TotalDays > 30)
18 {
19 Console.WriteLine("This directory is over a month old.");
20 }
21 else if (DateTime.Now.Subtract(dt).TotalDays <= 1)
22 {
23 Console.WriteLine("This directory is less than a day old.");
24 }
25 else
26 {
27 Console.WriteLine("This directory was created on {0}", dt);
28 }
29 }
30 catch (Exception e)
31 {
32 Console.WriteLine("The process failed: {0}", e.ToString());
33 }
34 }
35 }
目录的相关操作
向一个Form窗体上拖拽五个Button控件,Button控件的text属性设置为“创建目录”、“删除目录”、“移动目录”、“目录创建时间”、“返回指定目录文件”

在类Form3里添加二个静态字段directory_path、directory_otherpath,都为string类型,分别代表工作目录路径和其他目录路径;双击“创建目录”、“删除目录”、“移动目录”、“目录创建时间”、“返回指定目录文件”

1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Text;
7 using System.Windows.Forms;
8 using System.IO;
9
10 namespace FileOptionApplication
11 {
12 public partial class Form3 : Form
13 {
14 public Form3()
15 {
16 InitializeComponent();
17 }
18 private static string directory_path = "c:\\qs250";
19 private static string directory_otherpath = "c:\\qqqq";
20 /// <summary>
21 /// 删除目录鼠标单击事件
22 /// </summary>
23 private void button1_Click(object sender, EventArgs e)
24 {
25 try
26 {
27 Directory.CreateDirectory(directory_path);
28 button2.Enabled = true;
29 button1.Enabled = false;
30 button3.Enabled = true;
31 button4.Enabled = true;
32 button5.Enabled = true;
33 MessageBox.Show("文件夹成功建立。", "警报");
34 }
35 catch (Exception mm)
36 {
37 MessageBox.Show("磁盘操作错误,原因:" + Convert.ToString(mm), "警报");
38 }
39 }
40 /// <summary>
41 /// 删除目录鼠标单击事件
42 /// </summary>
43 private void button2_Click(object sender, EventArgs e)
44 {
45 try
46 {
47 Directory.Delete(directory_path);
48 button2.Enabled = false;
49 button1.Enabled = true;
50 button3.Enabled = false;
51 button4.Enabled = false;
52 button5.Enabled = false;
53 MessageBox.Show("文件夹删除建立。", "警报");
54 }
55 catch (Exception mm)
56 {
57 MessageBox.Show("磁盘操作错误,原因:" + Convert.ToString(mm), "警报");
58 }
59 }
60 /// <summary>
61 /// 移动目录鼠标单击事件
62 /// </summary>
63 private void button3_Click(object sender, EventArgs e)
64 {
65 try
66 {
67 Directory.Move(directory_path, directory_otherpath);
68 MessageBox.Show("文件夹移动成功。", "警报");
69 //举例来讲,如果您尝试将c:\mydir 移到c:\public,并且c:\public 已存在,
70 //则此方法引发IOException。您必须将“c:\\public\\mydir”指定为destDirName 参数,或者指定新目录名,例如“c:\\newdir”。
71 }
72 catch (Exception mm)
73 {
74 MessageBox.Show("磁盘操作错误,原因:" + Convert.ToString(mm), "警报");
75 }
76 }
77 /// <summary>
78 /// 目录创建时间鼠标单击事件
79 /// </summary>
80 private void button4_Click(object sender, EventArgs e)
81 {
82 try
83 {
84 MessageBox.Show(string.Format("{0:G}",Directory.GetCreationTime(directory_path)), "提示");
85 //获取时间格式参见DateTimeFormatInfo
86 }
87 catch (Exception mm)
88 {
89 MessageBox.Show("磁盘操作错误,原因:" + Convert.ToString(mm), "警报");
90 }
91 }
92 /// <summary>
93 /// 返回指定目录文件鼠标单击事件
94 /// </summary>
95 private void button5_Click(object sender, EventArgs e)
96 {
97 try
98 {
99 string[] fileEntries = Directory.GetFiles(directory_path);
100 if (fileEntries.Length != 0)
101 {
102 foreach (string s in fileEntries)
103 {
104 if (File.Exists(s))
105 {
106 MessageBox.Show("内有文件信息:" + s, "提示");
107 }
108 }
109 }
110 else
111 {
112 MessageBox.Show("空文件夹", "提示");
113 }
114 //获取时间格式参见DateTimeFormatInfo
115 }
116 catch (Exception mm)
117 {
118 MessageBox.Show("磁盘操作错误,原因:" + Convert.ToString(mm), "警报");
119 }
120 }
121 }
122 }
1.4 file类读取文本文件的方法
|
方法
|
说明
|
|
CreateText(string FilePath)
|
创建或打开一个文件用于写入 UTF-8 编码的文本。
|
|
OpenText(string FilePath)
|
打开现有 UTF-8 编码文本文件以进行读取。
|
|
Open(string FilePath, FileMode)
|
打开指定路径上的 FileStream,具有读/写访问权限。
|
|
Create(string FilePath)
|
在指定路径中创建文件。
|
|
OpenRead(string FilePath)
|
打开现有文件以进行读取。
|
|
AppendText(string FilePath)
|
创建一个 StreamWriter,它将 UTF-8 编码文本追加到现有文件。
|
案例写一个记事本
向一个Form窗体上拖拽两个GroupBox控件,text属性分别设置为“写入文本”、“命名文本文件:”;向两个GroupBox控件里拖拽一个RichTextBox控件和一个TextBox控件;向第一个GroupBox控件里拖拽二个Button控件,属性分别设置为“保存编辑文件”、“打开文本文件”;向第二个GroupBox控件里拖拽一个Button控件,text属性设置为“创建文本文件”

在案例中添加一个静态字段directory_path,string类型,代表工作目录路径;双击“保存编辑文件”、“打开文本文件”、“创建文本文件”,在click事件处理方法里分别添加代码如下:

1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Text;
7 using System.Windows.Forms;
8 using System.IO;
9
10 namespace FileOptionApplication
11 {
12 public partial class Form4 : Form
13 {
14 public Form4()
15 {
16 InitializeComponent();
17 }
18 private static string directory_path = "c:\\";
19 /// <summary>
20 /// 创建文本文件
21 /// </summary>
22 private void button1_Click(object sender, EventArgs e)
23 {
24 try
25 {
26 if (textBox1.Text.Length == 0)
27 {
28 MessageBox.Show("文件名禁止为空!", "警报");
29 }
30 else
31 {
32 directory_path = directory_path + textBox1.Text.Trim() + ".txt";
33 //File.CreateText(..)返回的是一个StreamWriter
34 StreamWriter sw = File.CreateText(directory_path);
35 button2.Enabled = true;
36 button3.Enabled = true;
37 button1.Enabled = false;
38 richTextBox1.Enabled = true;
39 MessageBox.Show("文件文件成功建立。", "消息");
40 sw.Close();
41 }
42 }
43 catch (Exception mm)
44 {
45 MessageBox.Show("磁盘操作错误,原因:" + Convert.ToString(mm), "警报");
46 }
47 }
48 /// <summary>
49 /// 打开文本文件
50 /// </summary>
51 private void button2_Click(object sender, EventArgs e)
52 {
53 try
54 {
55 OpenFileDialog open = new OpenFileDialog();//创建一个打开的对话框
56 open.Title = "打开文本文件";
57 open.FileName = "";
58 open.AddExtension = true;//设置是否自动在文件中添加扩展名
59 open.CheckFileExists = true;//检查文件是否存在
60 open.CheckPathExists = true;//验证路径有效性
61 open.Filter = "文本文件(*.txt)|*.txt";//设置将打开文件的类型
62 open.ValidateNames = true;
63 //文件有效性验证ValidateNames,验证用户输入是否是一个有效的Windows文件名
64 if (open.ShowDialog() == DialogResult.OK)
65 {
66 StreamReader sr = new StreamReader(open.FileName, System.Text.Encoding.Default);
67 this.richTextBox1.Text = sr.ReadToEnd();
68 }
69 MessageBox.Show("文件打开成功。", "消息");
70 }
71 catch (Exception mm)
72 {
73 MessageBox.Show("磁盘操作错误,原因:" + Convert.ToString(mm), "警报");
74 }
75 }
76 /// <summary>
77 /// 保存编辑文件
78 /// </summary>
79 private void button3_Click(object sender, EventArgs e)
80 {
81 try
82 {
83 FileStream textfile = File.Open(directory_path, FileMode.OpenOrCreate, FileAccess.Write);
84 StreamWriter sw = new StreamWriter(textfile, Encoding.GetEncoding("GB2312"));
85 sw.Write(richTextBox1.Text.ToString());
86 MessageBox.Show("文件写成功。", "警报");
87 }
88 catch (Exception mm)
89 {
90 MessageBox.Show("磁盘操作错误,原因:" + Convert.ToString(mm), "警报");
91 }
92 }
93 }
94 }
1.5FileStream 文件流
用File类提供的方法在创建或打开文件时,总是会产生一个FileStream对象。
(1)使用File对象的Create方法

1 FileStream mikecatstream;
2 mikecatstream = File.Create("c:\\mikecat.txt");
3 //本段代码的含义:
4 //利用类File的Create()方法在C:根目录下创建文件mikecat.txt,并把文件流赋给mikecatstream
(2) 使用File对象的Open方法,‘

1 FileStream mikecatstream;
2 mikecatstream = File.Open("c:\\mikecat.txt", FileMode.OpenOrCreate, FileAccess.Write);
3 //本段代码的含义:
4 //利用类File的Open()方法打开在C:根目录下的文件mikecat.txt,打开的模式为打开或创建,对文件的访问形式为只写,并把文件流赋给mikecatstream。
(3) 使用类FileStream的构造函数

1 FileStream mikecatstream;
2 mikecatstream = new FileStream("c:\\mikecat.txt", FileMode.OpenOrCreate, FileAccess.Write);
3 //本段代码的含义:
4 //利用类FileStream的构造函数打开在C:根目录下的文件mikecat.txt,打开的模式为打开或创建,对文件的访问形式为只写,并把文件流赋给mikecatstream。
最常用的构造函数
|
名称
|
说明
|
|
FileStream(string FilePath, FileMode)
|
使用指定的路径和创建模式初始化 FileStream 类的新实例。
|
|
FileStream(string FilePath, FileMode, FileAccess)
|
使用指定的路径、创建模式和读/写权限初始化 FileStream 类的新实例。
|
|
FileStream(string FilePath, FileMode, FileAccess, FileShare)
|
使用指定的路径、创建模式、读/写权限和共享权限创建 FileStream 类的新实例。
|
构造函数中使用的枚举类型
|
名称
|
取值
|
说明
|
|
FileMode
|
Append、Create、CreateNew、Open、OpenOrCreate和Truncate
|
指定操作系统打开文件的方式。
|
|
FileAccess
|
Read、ReadWrite和Write
|
定义用于控制对文件的读访问、写访问或读/写访问的常数。
|
|
FileShare
|
Inheritable、None、Read、ReadWrite和Write
|
包含用于控制其他 FileStream 对象对同一文件可以具有的访问类型的常数。
|
实例

1 FileStream fstream = new FileStream("Test.cs", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
2 //本段代码的含义:
3 //利用类FileStream的构造函数打开当前目录下的文件Test.cs,打开的模式为打开或创建,对文/的访问形式为读写,共享模式为拒绝共享,并把文件流赋给fstream。
关于FileMode和FileAccess,FileShare这三个枚举类型值
|
成员名称
|
说明
|
|
Append
|
打开现有文件并查找到文件尾,或创建新文件。FileMode.Append 只能同 FileAccess.Write 一起使用。任何读尝试都将失败并引发 ArgumentException。
|
|
Create
|
指定操作系统应创建新文件。如果文件已存在,它将被改写。这要求 FileIOPermissionAccess.Write。System.IO.FileMode.Create 等效于这样的请求:如果文件不存在,则使用 CreateNew;否则使用 Truncate。
|
|
CreateNew
|
指定操作系统应创建新文件。此操作需要 FileIOPermissionAccess.Write。如果文件已存在,则将引发 IOException。
|
|
Open
|
指定操作系统应打开现有文件。打开文件的能力取决于 FileAccess 所指定的值。如果该文件不存在,则引发 System.IO.FileNotFoundException。
|
|
OpenOrCreate
|
指定操作系统应打开文件(如果文件存在);否则,应创建新文件。如果用 FileAccess.Read 打开文件,则需要 FileIOPermissionAccess.Read。如果文件访问为FileAccess.Write 或 FileAccess.ReadWrite,则需要 FileIOPermissionAccess.Write。如果文件访问为 FileAccess.Append,则需要 FileIOPermissionAccess.Append。
|
|
Truncate
|
指定操作系统应打开现有文件。文件一旦打开,就将被截断为零字节大小。此操作需要 FileIOPermissionAccess.Write。试图从使用 Truncate 打开的文件中进行读取将导致异常。
|
|
成员名称
|
说明
|
|
Read
|
对文件的读访问。可从文件中读取数据。同 Write 组合即构成读写访问权。
|
|
ReadWrite
|
对文件的读访问和写访问。可从文件读取数据和将数据写入文件。
|
|
Write
|
文件的写访问。可将数据写入文件。同 Read 组合即构成读/写访问权。
|
|
成员名称
|
说明
|
|
Delete
|
允许随后删除文件。
|
|
Inheritable
|
使文件句柄可由子进程继承。Win32 不直接支持此功能。
|
|
None
|
谢绝共享当前文件。文件关闭前,打开该文件的任何请求(由此进程或另一进程发出的请求)都将失败。
|
|
Read
|
允许随后打开文件读取。如果未指定此标志,则文件关闭前,任何打开该文件以进行读取的请求(由此进程或另一进程发出的请求)都将失败。但是,即使指定了此标志,仍可能需要附加权限才能够访问该文件。
|
|
ReadWrite
|
允许随后打开文件读取或写入。如果未指定此标志,则文件关闭前,任何打开该文件以进行读取或写入的请求(由此进程或另一进程发出)都将失败。但是,即使指定了此标志,仍可能需要附加权限才能够访问该文件。
|
|
Write
|
允许随后打开文件写入。如果未指定此标志,则文件关闭前,任何打开该文件以进行写入的请求(由此进程或另一进过程发出的请求)都将失败。但是,即使指定了此标志,仍可能需要附加权限才能够访问该文件。
|
|
对于FileMode,如果要求的模式与文件的现有状态不一致,就会抛出一个异常。如果文件不存在,Append、Open和Truncate会抛出一个异常,如果文件存在,CreateNew会抛出一个异常。Create和OpenOrCreate可以处理这两种情况,但Create会删除现有的文件,创建一个新的空文件。FileAccess 和FileShare枚举是按位标志,所以这些值可以与C#的按位OR运算符|合并使用。
|
1****2 文件的读写
通过一个窗体,如图3-7所示,在点击相应按钮控件时,可以完成对文件的读写操作、磁盘操作以及对目录的管理操作。通过本案例使读者快速掌握操作文件、目录的技术方法及类FileStream的应用。
从工具箱之中拖拽五个GroupBox控件到Form窗体上,text属性分别设置为:“文件管理”、“读写文件操作”、“文件磁盘操作”、“设置文件属性”、“目录管理”;向第一个GroupBox控件拖拽一个RichTextBox控件;再向第一个GroupBox控件拖拽一个Button控件,text属性设置为“关闭”;向第二个GroupBox控件拖拽一个ComboBox控件,text属性设置为“写入类型选择:”,Items属性中添加“创建空文本文件”、“添加入文本文件”、“新写入文本文件”;再向第二个GroupBox控件拖拽二个Button控件,text属性分别设置为“写入文件”、“读出文件”;向第三个GroupBox控件拖拽一个ComboBox控件,text属性设置为“文件磁盘操作选择:”,Items属性中添加“文件创建”、“文件删除”、“文件复制”、“文件移动”;再向第三个GroupBox控件拖拽一个Button控件,text属性设置为“文件磁盘操作”;向第四个GroupBox控件拖拽二个CheckBox控件,text属性分别设置为“只读”、“隐藏”;再向第四个GroupBox控件拖拽一个Button控件,text属性设置为“属性确认”;向第五个GroupBox控件拖拽一个ComboBox控件,text属性分别设置为“文件目录操作选择:”,Items属性中添加“创建文件夹”、“文件夹删除”、“文件夹移动”、“获取子文件信息”;再向第五个GroupBox控件拖拽一个Button控件,text属性设置为“文件目录操作”。

代码

1 //=========================第一部分:主界面功能设计=============================
2 using System;
3 using System.Collections.Generic;
4 using System.ComponentModel;
5 using System.Data;
6 using System.Drawing;
7 using System.Text;
8 using System.Windows.Forms;
9 using System.IO;
10
11 namespace FileOptionApplication
12 {
13 public partial class Form6 : Form
14 {
15 public Form6()
16 {
17 InitializeComponent();
18 }
19 /// <summary>
20 /// 读写文件操作
21 /// </summary>
22 private void button3_Click(object sender, EventArgs e)
23 {
24 int p = comboBox1.SelectedIndex;
25 if (p == -1)
26 {
27 MessageBox.Show("请您选择文件写入方式", "警告信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
28 }
29 else
30 {
31 string filecontent = richTextBox1.Text.Trim();
32 MyFileOption myoption = new MyFileOption();
33 string filepath = @"c:\1.txt";
34 bool i = myoption.WriteTextFile(filepath, filecontent, Convert.ToInt16(comboBox1.SelectedIndex));
35 if (i == true)
36 {
37 MessageBox.Show("保存成功", "保存信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
38 }
39 else
40 {
41 MessageBox.Show("写入文件时出错", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
42 }
43 }
44 }
45 /// <summary>
46 /// 文件磁盘操作
47 /// </summary>
48 private void button4_Click(object sender, EventArgs e)
49 {
50 Int16 p = Convert.ToInt16(comboBox2.SelectedIndex);
51 if (p == -1)
52 {
53 MessageBox.Show("请您选择磁盘文件操作方式", "警告信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
54 }
55 else
56 {
57 string sourcepath = "c:\\1.txt";
58 string targetpath = "c:\\2.txt";
59 MyFileOption myoption = new MyFileOption();
60 bool i = myoption.DiskFileOption(sourcepath, targetpath, p);
61 if (i == true)
62 {
63 MessageBox.Show("磁盘文件操作成功", "保存信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
64 }
65 else
66 {
67 MessageBox.Show("磁盘文件操作时出错", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
68 }
69 }
70 }
71 private void button1_Click(object sender, EventArgs e)
72 {
73 richTextBox1.Text = null;
74 richTextBox1.Focus();
75 }
76 /// <summary>
77 /// 读出文本文件内容
78 /// </summary>
79 private void button2_Click(object sender, EventArgs e)
80 {
81 MyFileOption myoption = new MyFileOption();
82 string filepath = @"c:\1.txt";
83 Int16 i = 0;
84 string filecontent = "";
85 myoption.ReadTextFile(filepath, out i, out filecontent);
86 if (i == 0)
87 {
88 MessageBox.Show(filecontent, "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
89 richTextBox1.Text = filecontent;
90 }
91 else if (i == 1)
92 {
93 richTextBox1.Text = filecontent;
94 MessageBox.Show("读取文件成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Warning);
95 }
96 else if (i == 2)
97 {
98 richTextBox1.Text = filecontent;
99 MessageBox.Show(filecontent, "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
100 }
101 }
102 /// <summary>
103 /// 文件基本属性设置
104 /// </summary>
105 private void button5_Click(object sender, EventArgs e)
106 {
107 string filepath = @"c:\1.txt";
108 if (checkBox1.Checked && checkBox2.Checked)
109 {
110 File.SetAttributes(filepath, FileAttributes.ReadOnly | FileAttributes.Hidden);
111 MessageBox.Show("文件已经改为只读且隐藏", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
112 }
113 else
114 {
115 if (!checkBox1.Checked && !checkBox2.Checked)
116 {
117 File.SetAttributes(filepath, FileAttributes.Archive);
118 MessageBox.Show("文件已经改为正常", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
119 }
120 else
121 {
122 if (checkBox2.Checked)
123 {
124 File.SetAttributes(filepath, FileAttributes.ReadOnly);
125 MessageBox.Show("文件已经改为只读", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
126 }
127 if (checkBox1.Checked)
128 {
129 File.SetAttributes(filepath, FileAttributes.Hidden);
130 MessageBox.Show("文件已经改为隐藏", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
131 }
132 }
133 }
134 }
135 /// <summary>
136 /// 文件夹操作
137 /// </summary>
138 private void button6_Click(object sender, EventArgs e)
139 {
140 Int16 p = Convert.ToInt16(comboBox3.SelectedIndex);
141 if (p == -1)
142 {
143 MessageBox.Show("请您选择文件夹操作方式", "警告信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
144 }
145 else
146 {
147 string sourcepath = @"c:\1";
148 string targetpath = @"c:\2";
149 MyFileOption myoption = new MyFileOption();
150 string[] filesname = null;
151 bool i = myoption.DirectoryOption(sourcepath, targetpath, p, out filesname);
152 if (i == true)
153 {
154 MessageBox.Show("磁盘文件夹操作成功", "保存信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
155 if (filesname != null)
156 {
157 foreach (string somestring in filesname)
158 {
159 richTextBox1.Text += somestring + "\r\n";
160 }
161 }
162 }
163 else
164 {
165 MessageBox.Show("磁盘文件夹操作时出错", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
166 }
167 }
168 }
169 }
170 }

向FileOption.cs文件中添加代码如下:

1 //==============================第二部分:类设计============================
2 using System;
3 using System.Collections.Generic;
4 using System.Text;
5 using System.IO;
6
7 namespace FileOptionApplication
8 {
9 class MyFileOption
10 {
11 /// <summary>
12 /*******************************************************
13 **方法 名:WriteTextFile
14 **输入参数:filepath:文件路径;
15 ** filecontent:写入文件的内容
16 ** WriteMethord:写入方法(0:打开并创建文件;1:添加文本;2:新建文本)
17 **输出参数:逻辑类型参数
18 **返 回 值:bool
19 **创建 人:钱哨
20 **创建日期:09-7-9
21 **描 述:打开存放在某目录下名称为filepath文件,并在该文件中写入filecontent。
22 *******************************************************/
23 public bool WriteTextFile(string filepath, string filecontent, Int16 WriteMethord)
24 {
25 bool i = true;
26 try
27 {
28 if (WriteMethord == 0)
29 {
30 FileStream textfile = File.Open(filepath, FileMode.OpenOrCreate, FileAccess.Write);
31 StreamWriter sw = new StreamWriter(textfile, Encoding.Default);
32 sw.Write(filecontent);
33 i = true;
34 sw.Close();
35 textfile.Close();
36 }
37 else if (WriteMethord == 1)
38 {
39 FileStream textfile = File.Open(filepath, FileMode.Append, FileAccess.Write);
40 StreamWriter sw = new StreamWriter(textfile, Encoding.Default);
41 sw.Write(filecontent);
42 i = true;
43 sw.Close();
44 textfile.Close();
45 }
46 else if (WriteMethord == 2)
47 {
48 FileStream textfile = File.Open(filepath, FileMode.Create, FileAccess.Write);
49 StreamWriter sw = new StreamWriter(textfile, Encoding.Default);
50 sw.Write(filecontent);
51 i = true;
52 sw.Close();
53 textfile.Close();
54 }
55 return i;
56 }
57 catch
58 {
59 i = false;
60 return i;
61 }
62 }
63 /// <summary>
64 /*******************************************************
65 **方法 名:DiskFileOption
66 **输入参数:SourcePath:源文件路径;
67 ** TargetPath:目的文件路径;
68 ** OptionMethord:操作类别;0:文件创建;1:文件删除;2:文件复制;3:文件移动
69 **输出参数:逻辑类型参数
70 **返 回 值:bool
71 **创 建 人:钱哨
72 **创建日期:09-7-9
73 **描 述:对磁盘文件实施基本操作。
74 *******************************************************/
75 public bool DiskFileOption(string SourcePath, string TargetPath, Int16 OptionMethord)
76 {
77 bool i = true;
78 try
79 {
80 if (OptionMethord == 0)
81 {
82 //文件创建
83 FileStream textfile = File.Create(SourcePath);
84 textfile.Close();
85 }
86 else if (OptionMethord == 1)
87 {
88 //文件删除
89 File.Delete(SourcePath);
90 }
91 else if (OptionMethord == 2)
92 {
93 //文件复制
94 File.Copy(SourcePath, TargetPath, true);
95 }
96 else if (OptionMethord == 3)
97 {
98 //文件移动
99 File.Move(SourcePath,TargetPath);
100 }
101 return i;
102 }
103 catch
104 {
105 i = false;
106 return i;
107 }
108 }
109
110 /// <summary>
111 /*******************************************************
112 **方法 名:ReadTextFile
113 **输入参数:filepath:文件路径;
114 **输出参数:i:读取类型(1:正常;2:文件读取错误;3:文件或路径无效);
115 ** filecontent:返回内容
116 **返 回 值:逻辑类型参数
117 **创 建 人:钱哨
118 **创建日期:09-7-9
119 **描 述:读取存放在某目录下名称为filepath文件内容。
120 *******************************************************/
121 public void ReadTextFile(string filepath, out Int16 i, out string filecontent)
122 {
123 if (File.Exists(filepath))
124 {
125 try
126 {
127 StreamReader textreader = new StreamReader(filepath, System.Text.Encoding.Default);
128 filecontent = textreader.ReadToEnd();
129 textreader.Close();
130 i = 1;
131 }
132 catch
133 {
134 i = 2;
135 filecontent = "文件读取错误!";
136 }
137 }
138 else
139 {
140 i = 0;
141 filecontent = "文件或路径无效!";
142 }
143 }
144 /// <summary>
145 /*******************************************************
146 **方法 名:DirectoryOption
147 **输入参数:filepath:文件路径;
148 **输出参数:i:读取类型 (0:创建文件夹;1:文件夹删除;2:文件夹移动;3:获取文件夹下面所有的子文件信息) filecontent:返回内容
149 **返 回 值:逻辑类型参数
150 **创 建 人:钱哨
151 **创建日期:09-7-9
152 **描 述:读取存放在某目录下名称为filepath文件内容。
153 *******************************************************/
154 /// <summary>
155 public bool DirectoryOption(string Directorypath, string TargetDirectorypath, Int16 OptionMethord, out string[] filesname)
156 {
157 bool k = true;
158 filesname = null;
159 if (Directory.Exists(Directorypath))
160 {
161 try
162 {
163 if (OptionMethord == 0)
164 {
165 //创建文件夹
166 Directory.CreateDirectory(Directorypath);
167 }
168 else if (OptionMethord == 1)
169 {
170 //文件夹删除
171 Directory.Delete(Directorypath, true);
172 }
173 else if (OptionMethord == 2)
174 {
175 //文件夹移动
176 Directory.Move(Directorypath, TargetDirectorypath);
177 }
178 else if (OptionMethord == 3)
179 {
180 //获取文件夹下面所有的子文件信息
181 filesname = Directory.GetFiles(Directorypath);
182 }
183 }
184 catch
185 {
186 k = false;
187 }
188 }
189 else
190 {
191 Directory.CreateDirectory(Directorypath);
192 k = true;
193 }
194 return k;
195 }
196 }
197 }
文件流FileStream综合案例
从工具箱之中拖拽三个GroupBox控件到Form窗体上,text属性分别设置为:“添加物理路径”、“打开文本文件”、“文本编辑区”;向第一个GroupBox控件拖拽一个TextBox控件;再向第一个GroupBox控件拖拽一个Button控件,text属性设置为“选定文件夹”;向第二个GroupBox控件拖拽一个TextBox控件;再向第二个GroupBox控件拖拽一个Button控件,text属性设置为“选定文件”;向第三个GroupBox控件拖拽一个richTextBox控件;再向窗体上非GroupBox区域拖拽一个Button控件,text属性设置为“保存文本文件”。


1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Text;
7 using System.Windows.Forms;
8 using System.IO;
9
10 namespace FileOptionApplication
11 {
12 public partial class Form11 : Form
13 {
14 public Form11()
15 {
16 InitializeComponent();
17 }
18 //添加变量TypeW,int类型,0为默认,1为打开文件夹并建立new.txt文件,2为打开文本文件
19 int TypeW = 0;
20 /// <summary>
21 /// 选定某个文件夹
22 /// </summary>
23 private void button1_Click(object sender, EventArgs e)
24 {
25 //新建文件夹
26 FolderBrowserDialog openfolder = new FolderBrowserDialog();
27 if (openfolder.ShowDialog ()== DialogResult.OK)
28 {
29 textBox1.Text = Convert.ToString(openfolder.SelectedPath);
30 TypeW = 1;
31 }
32 }
33 /// <summary>
34 /// 选定某个文件夹下面的文本文件
35 /// </summary>
36 private void button4_Click(object sender, EventArgs e)
37 {
38 OpenFileDialog openfile = new OpenFileDialog();
39 openfile.Filter = "文本文件|*.txt";
40 if (openfile.ShowDialog() == DialogResult.OK)
41 {
42 FileStream OpenFileStream = new FileStream(openfile.FileName, FileMode.Open, FileAccess.Read);
43 StreamReader sr = new StreamReader(OpenFileStream, Encoding.Default);
44 richTextBox1.Text = sr.ReadToEnd();
45 textBox2.Text = Convert.ToString(openfile.FileName);
46 OpenFileStream.Close();
47 sr.Close();
48 TypeW = 2;
49 }
50 }
51 /// <summary>
52 /// 保存文本文件
53 /// </summary>
54 private void button2_Click(object sender, EventArgs e)
55 {
56 if (richTextBox1.Text == string.Empty)
57 {
58 MessageBox.Show("编辑文本文件内容禁止为空!", "提示信息");
59 return;
60 }
61 else
62 {
63 if (TypeW == 1)
64 {
65 FileStream fs = new FileStream(textBox1.Text+@"\\new.txt",FileMode.Create,FileAccess.ReadWrite);
66 StreamWriter sw = new StreamWriter(fs,Encoding.Default);
67 sw.Write(richTextBox1.Text);
68 TypeW = 0;
69 MessageBox.Show("已经成功的将文本文件写入" + textBox1.Text + "\\new.txt之中", "提示信息");
70 //注意:此处顺序绝不可调换,为什么?【另外,为什么必须关闭线程资源?】
71 sw.Close();
72 fs.Close();
73 }
74 else if(TypeW==2)
75 {
76 FileStream fs = new FileStream(textBox2.Text, FileMode.OpenOrCreate, FileAccess.ReadWrite);
77 StreamWriter sw = new StreamWriter(fs, Encoding.Default);
78 sw.Write(richTextBox1.Text);
79 TypeW = 0;
80 MessageBox.Show("已经成功的将文本文件写入" + textBox2.Text + "之中", "提示信息");
81 //注意:此处顺序绝不可调换,为什么?
82 sw.Close();
83 fs.Close();
84 }
85 }
86 }
87 }
88 }
4 读取二进制
|
FileStream filestream = new FileStream(Filename, FileMode.Create);
BinaryWriter objBinaryWriter = new BinaryWriter(filestream);
|
常用方法:
|
方法
|
说明
|
|
Close()
|
关闭当前阅读器及基础流。
|
|
Read()
|
已重载。 从基础流中读取字符,并提升流的当前位置。
|
|
ReadDecimal()
|
从当前流中读取十进制数值,并将该流的当前位置提升十六个字节。
|
|
ReadByte()
|
从当前流中读取下一个字节,并使流的当前位置提升1个字节。
|
|
ReadInt16()
|
从当前流中读取2字节有符号整数,并使流的当前位置提升2个字节。
|
|
ReadInt32()
|
从当前流中读取4字节有符号整数,并使流的当前位置提升4个字节。
|
|
ReadString()
|
从当前流中读取一个字符串。字符串有长度前缀,一次7位地被编码为整数。
|
实例:建立一个BinaryReader类的一些主要方法

1 using System;
2 using System.IO;
3
4 class BinaryRW
5 {
6 static void Main()
7 {
8 int i = 0;
9 char[] invalidPathChars = Path.InvalidPathChars;
10 MemoryStream memStream = new MemoryStream();
11 BinaryWriter binWriter = new BinaryWriter(memStream);
12 // 写入内存
13 binWriter.Write("Invalid file path characters are: ");
14 for (i = 0; i < invalidPathChars.Length; i++)
15 {
16 binWriter.Write(invalidPathChars[i]);
17 }
18 // 用作生成编写器的内存流同样作为生成读取器的内存流
19 BinaryReader binReader = new BinaryReader(memStream);
20 // 设置流的起点
21 memStream.Position = 0;
22 // 从内存中读取数据,并把数据写入控制台
23 Console.Write(binReader.ReadString());
24 char[] memoryData = new char[memStream.Length - memStream.Position];
25 for (i = 0; i < memoryData.Length; i++)
26 {
27 memoryData[i] = Convert.ToChar(binReader.Read());
28 }
29 Console.WriteLine(memoryData);
30 }
31 }
类BinaryWriter以二进制形式将基元类型写入流,并支持用特定的编码写入字符串。
|
方法
|
说明
|
|
Close()
|
关闭当前的 BinaryWriter 和基础流。
|
|
Flush()
|
清理当前编写器的所有缓冲区,使所有缓冲数据写入基础设备。
|
|
Write()
|
已重载。 将值写入当前流。
|
建立一个BinaryWriter类方法

1 using System;
2 using System.IO;
3
4 class BinaryRW
5 {
6 static void Main()
7 {
8 using (BinaryWriter binWriter = new BinaryWriter(File.Open(fileName, FileMode.Create)))
9 {
10 binWriter.Write(aspectRatio);
11 binWriter.Write(lookupDir);
12 binWriter.Write(autoSaveTime);
13 binWriter.Write(showStatusBar);
14 }
15 }
16 }
4.2 写二进制文件
从工具箱之中拖拽MainMenu控件、SaveFileDialog控件、GroupBox控件、PictureBox控件各一个到Form窗体上;Form窗体的text属性设置为“图片处理器”;GroupBox控件的text属性设置为“图片显示区”;PictureBox控件的sizemode属性设置为zoom;MainMenu控件添加菜单项及子项:
|
菜单项
|
子项
|
其他属性
|
|
图片(&P)
|
打开图片(&O)
|
快捷键等其他属性根据自己设计定(下同)
|
|
复制图片(&C)
|
|
|
|
关闭(&Q)
|
|
|


1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Text;
7 using System.Windows.Forms;
8 using System.IO;
9
10 namespace FileOptionApplication
11 {
12 public partial class Form12 : Form
13 {
14 public Form12()
15 {
16 InitializeComponent();
17 }
18 /// <summary>
19 /*******************************************************
20 **方 法 名:GetFileBytes
21 **输 入参数:Filename:文件名称;
22 **输 出参数:比特流类型
23 **返 回 值:byte[]二进制流
24 **创 建 人:钱哨
25 **创 建日期:09-7-9
26 **描 述:将读取的文件转化成为二进制流。
27 *******************************************************/
28 /// <summary>
29 /// </summary>
30 /// <param name="Filename">打开的图片具体路径及文件名称</param>
31 /// <returns>比特流类型</returns>
32 public byte[] GetFileBytes(string Filename)
33 {
34 if (Filename == "")
35 return null;
36 try
37 {
38 FileStream fileStream = new FileStream(Filename, FileMode.Open, FileAccess.Read);
39 BinaryReader binaryReader = new BinaryReader(fileStream);
40 byte[] fileBytes = binaryReader.ReadBytes((int)fileStream.Length);
41 binaryReader.Close();
42 fileStream.Close();
43 return fileBytes;
44 }
45 catch
46 {
47 return null;
48 }
49 }
50 /*******************************************************
51 **方 法 名:WriteFileBytes
52 **输 入参数:TargetFilename:目标文件名称;
53 **输 出参数:布尔类型:是否写成功
54 **返 回 值:byte[]二进制流
55 **创 建 人:钱哨
56 **创 建日期:09-7-9
57 **描 述:将读取的文件转化成为二进制流。
58 *******************************************************/
59 /// </summary>
60 /// <param name="TargetFilename">目标文件</param>
61 /// <param name="fileBytes">文件比特流</param>
62 /// <returns>布尔类型:是否写成功</returns>
63 public bool WriteFileBytes(string TargetFilename, byte[] fileBytes)
64 {
65 bool k = true;
66 if (TargetFilename != "" && fileBytes.Length != 0)
67 {
68 try
69 {
70 FileStream fileStream = new FileStream(TargetFilename, FileMode.OpenOrCreate, FileAccess.Write);
71 BinaryWriter binaryWriter = new BinaryWriter(fileStream);
72 binaryWriter.Write(fileBytes);
73 binaryWriter.Flush();
74 binaryWriter.Close();
75 fileStream.Close();
76 }
77 catch
78 {
79 k = false;
80 }
81 }
82 else
83 {
84 k = false;
85 }
86 return k;
87 }
88 /// <summary>
89 /// 菜单:打开图片
90 /// </summary>
91 private void toolStripMenuItem3_Click(object sender, EventArgs e)
92 {
93 try
94 {
95 OpenFileDialog openfile = new OpenFileDialog();
96 openfile.Filter = "jpg类型图片(*.jpg)|*.jpg|BMP类型图片(*.bmp)|*.bmp";
97 if (openfile.ShowDialog() == DialogResult.OK)
98 {
99 byte[] picbinary = GetFileBytes(openfile.FileName);
100 //第一步:打开图片文件,获得比特流
101 MemoryStream mempicstream = new MemoryStream(picbinary);
102 //第二步:将比特流还存在内存工作流中。
103 pictureBox1.Image = Image.FromStream(mempicstream);
104 //第三步:加载内存流到图片控件
105 mempicstream.Dispose();
106 mempicstream.Close();
107 }
108 }
109 catch (Exception m)
110 {
111 MessageBox.Show("读取图片出错,可能的问题是:"+Convert.ToString(m) ,"错误提示");
112 }
113 }
114 /// <summary>
115 /// 将打开的图片进行复制
116 /// </summary>
117 private void toolStripMenuItem4_Click(object sender, EventArgs e)
118 {
119 try
120 {
121 if (pictureBox1.Image == null)
122 {
123 MessageBox.Show("禁止图片为空时候另存信息。", "错误提示");
124 }
125 else
126 {
127 saveFileDialog1.Filter = "jpg类型图片(*.jpg)|*.jpg";
128 DialogResult result = saveFileDialog1.ShowDialog();
129 if (result == DialogResult.OK)
130 {
131 MemoryStream ms=new MemoryStream();
132 Bitmap bm = new Bitmap(pictureBox1.Image);
133 bm.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
134 byte[] bytes = ms.ToArray();
135 WriteFileBytes(saveFileDialog1.FileName, bytes);
136 MessageBox.Show("另存图片成功", "提示");
137 ms.Dispose();
138 ms.Close();
139 bm.Dispose();
140 }
141 }
142 }
143 catch (Exception m)
144 {
145 MessageBox.Show("读取图片出错,可能的问题是:" + Convert.ToString(m), "错误提示");
146 }
147 }
148 }
149 }
成功
3.5读写内存流
5-1 读写内存流 ——MemoryStream类
|
名称
|
说明
|
|
MemoryStream ()
|
使用初始化为零的可扩展容量初始化 MemoryStream 类的新实例。
|
|
MemoryStream (byte[])
|
基于指定的字节数组初始化 MemoryStream 类的无法调整大小的新实例。
|
|
MemoryStream (byte[], Boolean)
|
使用按指定要求设置的 CanWrite 属性基于指定的字节数组初始化 MemoryStream 类的无法调整大小的新实例。
|
|
MemoryStream mem = new MemoryStream(buffer);
//这时,无法再设置Capacity属性的大小。
|
|
MemoryStream mem = new MemoryStream(buffer, false);
//这时,CanWrite属性就被设置为false 。
|
案例学习:MemoryStream类案例
从工具箱之中拖拽五个Label控件到Form窗体上,拖拽一个Button控件。

eg.

1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Text;
7 using System.Windows.Forms;
8 using System.IO;
9
10 namespace FileOptionApplication
11 {
12 public partial class Form14 : Form
13 {
14 public Form14()
15 {
16 InitializeComponent();
17 }
18 //建立字节数组
19 byte[] buffer = new byte[600];
20 /// <summary>
21 /// 获取测试性数据
22 /// </summary>
23 private void GetTestData()
24 {
25 for (int i = 0; i < 600; i++)
26 {
27 buffer[i] = (byte)(i % 256);
28 //byte类型的数最大不能超过255,用256取模实现
29 }
30 }
31 /// <summary>
32 /// button1按钮的鼠标单击Click事件
33 /// </summary>
34 private void button1_Click(object sender, EventArgs e)
35 {
36 //创建测试数据
37 GetTestData();
38 //创建内存流对象,初始分配50字节的缓冲区
39 MemoryStream mem = new MemoryStream(50);
40 //向内存流中写入字节数组的所有数据
41 mem.Write(buffer,0,buffer.GetLength(0));
42 //使用从缓冲区读取的数据将字节块写入当前流。
43 //参数:
44 //1、buffer从中写入数据的缓冲区。
45 //2、offset buffer中的字节偏移量,从此处开始写入。
46 //3、count最多写入的字节数。
47 //GetLength(0) 为 GetLength 的一个示例,它返回 Array 的第一维中的元素个数。
48 label1.Text = "写入数据后的内存流长度是:"+mem.Length.ToString();
49 label2.Text = "分配给内存流的缓冲区大小:"+mem.Capacity.ToString();
50 mem.SetLength(500);
51 label3.Text = "调用SetLength方法后的内存流长度:" + mem.Length.ToString();
52 mem.Capacity = 620;//注意:此值不能小于Length属性
53 label4.Text = "调用Capacity方法后缓冲区大小:" + mem.Capacity.ToString();
54 //将读写指针移到距流开头10个字节的位置
55 mem.Seek(45, SeekOrigin.Begin);
56 label5.Text = "内存中的信息是:"+mem.ReadByte().ToString();
57 }
58 }
59 }

5-3 读写缓存流 ——BufferedStream类
|
名称
|
说明
|
|
使用默认的缓冲区大小 4096 字节初始化 BufferedStream 类的新实例。
|
|
|
使用指定的缓冲区大小初始化 BufferedStream 类的新实例。
|
BufferedStream类案例学习
1. 案例学习:通过缓冲区交换数据
从工具箱之中拖拽一个GroupBox,text属性设置为“打开文件”;拖拽二个Label控件到GroupBox上,text属性分别设置为“请选择源文件名:”、“请填写备份文件名:”;拖拽二个TextBox控件到GroupBox上,其中第一TextBox控件的Enabled属性为false;拖拽二个Button控件到GroupBox上,text属性分别设置为“打开文件”、“备份文件”。


1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Text;
7 using System.Windows.Forms;
8 using System.IO;
9
10 namespace FileOptionApplication
11 {
12 public partial class Form16 : Form
13 {
14 public Form16()
15 {
16 InitializeComponent();
17 }
18 /// <summary>
19 /// 打开原始文件
20 /// </summary>
21 private void button1_Click(object sender, EventArgs e)
22 {
23 OpenFileDialog openfile = new OpenFileDialog();
24 openfile.Filter = "文本文件(*.txt)|*.txt";
25 if (openfile.ShowDialog() == DialogResult.OK)
26 {
27 textBox1.Text = openfile.FileName.ToString();
28 }
29 }
30 /// <summary>
31 /// 备份目标文件;Stream 和 BufferedStream 的实例
32 /// </summary>
33 private void button2_Click(object sender, EventArgs e)
34 {
35 string targetpath = @"c:\" + textBox2.Text + ".txt";
36 FileStream fs =File.Create(targetpath);
37 fs.Dispose();
38 fs.Close();
39 string sourcepath = textBox1.Text;
40 Stream outputStream= File.OpenWrite(targetpath);
41 Stream inputStream = File.OpenRead(sourcepath);
42 BufferedStream bufferedInput = new BufferedStream(inputStream);
43 BufferedStream bufferedOutput = new BufferedStream(outputStream);
44 byte[] buffer = new Byte[4096];
45 int bytesRead;
46 while ((bytesRead =bufferedInput.Read(buffer, 0,4096)) > 0)
47 {
48 bufferedOutput.Write(buffer, 0, bytesRead);
49 }
50 //通过缓冲区进行读写
51 MessageBox.Show("给定备份的文件已创建", "提示");
52 bufferedOutput.Flush();
53 bufferedInput.Close();
54 bufferedOutput.Close();
55 //刷新并关闭 BufferStream
56 }
57 }
58 }
文件流FileStream 上机实验
文本编辑器
mainMenu TextBox OpenFileDialog SaveFileDialog FontDialog colorDialog
代碼

1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Text;
7 using System.Windows.Forms;
8 using System.IO;
9
10 namespace FileOptionApplication
11 {
12 public partial class Form16 : Form
13 {
14 public Form16()
15 {
16 InitializeComponent();
17 }
18 /// <summary>
19 /// 打开原始文件
20 /// </summary>
21 private void button1_Click(object sender, EventArgs e)
22 {
23 OpenFileDialog openfile = new OpenFileDialog();
24 openfile.Filter = "文本文件(*.txt)|*.txt";
25 if (openfile.ShowDialog() == DialogResult.OK)
26 {
27 textBox1.Text = openfile.FileName.ToString();
28 }
29 }
30 /// <summary>
31 /// 备份目标文件;Stream 和 BufferedStream 的实例
32 /// </summary>
33 private void button2_Click(object sender, EventArgs e)
34 {
35 string targetpath = @"c:\" + textBox2.Text + ".txt";
36 FileStream fs =File.Create(targetpath);
37 fs.Dispose();
38 fs.Close();
39 string sourcepath = textBox1.Text;
40 Stream outputStream= File.OpenWrite(targetpath);
41 Stream inputStream = File.OpenRead(sourcepath);
42 BufferedStream bufferedInput = new BufferedStream(inputStream);
43 BufferedStream bufferedOutput = new BufferedStream(outputStream);
44 byte[] buffer = new Byte[4096];
45 int bytesRead;
46 while ((bytesRead =bufferedInput.Read(buffer, 0,4096)) > 0)
47 {
48 bufferedOutput.Write(buffer, 0, bytesRead);
49 }
50 //通过缓冲区进行读写
51 MessageBox.Show("给定备份的文件已创建", "提示");
52 bufferedOutput.Flush();
53 bufferedInput.Close();
54 bufferedOutput.Close();
55 //刷新并关闭 BufferStream
56 }
57 }
58 }
59
60
61 ————————————————————————————————
62 using System;
63 using System.Collections.Generic;
64 using System.ComponentModel;
65 using System.Data;
66 using System.Drawing;
67 using System.Text;
68 using System.Windows.Forms;
69
70 namespace WindowsApplication1
71 {
72 public partial class Form9 : Form
73 {
74 public Form8 mainForm;
75 public Form9()
76 {
77 InitializeComponent();
78 }
79 /// <summary>
80 /// 点击查询下一个后
81 /// </summary>
82 /// <param name="sender"></param>
83 /// <param name="e"></param>
84 private void btnFindNext_Click(object sender, EventArgs e)
85 {
86 mainForm.findKey = txtContent.Text;
87 mainForm.isToDown = radToDown.Checked;
88 mainForm.mathingStyle = checkBox1.Checked;
89 string source; //被查找的文本
90 string finding; //查找的关键字
91
92 //当不区分大小写时,将内容都转换为小写
93 if (this.checkBox1.Checked == false)
94 {
95 source = this.mainForm.textBox1.Text.ToLower();
96 finding = this.txtContent.Text.ToLower();
97 }
98 else
99 {
100 source = this.mainForm.textBox1.Text;
101 finding = this.txtContent.Text;
102 }
103
104 //向下查找
105 if (this.radToDown.Checked)
106 {
107 //SelectionStart能获取光标起始点
108 int temp = source.IndexOf(finding, mainForm.textBox1.SelectionStart + mainForm.textBox1.SelectedText.Length);
109 if (temp >= 0)
110 {
111 this.mainForm.textBox1.Select(temp, finding.Length);
112 mainForm.textBox1.ScrollToCaret();//当屏幕显示不了时,实现滚动
113 this.mainForm.Focus();
114 }
115 else
116 {
117 MessageBox.Show("没有找到" + "'" + txtContent.Text + "'");
118 }
119 }
120 //向上查找
121 else
122 {
123 int temp = -1;
124 try
125 {
126 temp = source.LastIndexOf(finding, mainForm.textBox1.SelectionStart - 1);
127 }
128 catch { }
129 if (temp >= 0)
130 {
131 this.mainForm.textBox1.Select(temp, finding.Length);
132 mainForm.textBox1.ScrollToCaret();//当屏幕显示不了时,实现滚动
133 this.mainForm.Focus();
134 }
135 else
136 {
137 MessageBox.Show("没有找到" + "'" + txtContent.Text + "'");
138 }
139 }
140 }
141 /// <summary>
142 /// 点击取消后
143 /// </summary>
144 /// <param name="sender"></param>
145 /// <param name="e"></param>
146 private void btnCancel_Click(object sender, EventArgs e)
147 {
148 this.Close();
149 }
150 /// <summary>
151 /// 当查询文本框文本内容发生变化后
152 /// </summary>
153 /// <param name="sender"></param>
154 /// <param name="e"></param>
155 private void txtContent_TextChanged(object sender, EventArgs e)
156 {
157 if (txtContent.Text.Length > 0)
158 {
159 btnFindNext.Enabled = true;
160 }
161 else
162 {
163 btnFindNext.Enabled = false;
164 }
165 }
166 /// <summary>
167 /// 表单初始化事件
168 /// </summary>
169 /// <param name="sender"></param>
170 /// <param name="e"></param>
171 private void Form9_Load(object sender, EventArgs e)
172 {
173 txtContent.Text = mainForm.textBox1.SelectedText;
174 }
175
176 }
177 }
178 —————————————————————————————————
179
180 using System;
181 using System.Collections.Generic;
182 using System.ComponentModel;
183 using System.Data;
184 using System.Drawing;
185 using System.Text;
186 using System.Windows.Forms;
187
188 namespace WindowsApplication1
189 {
190 public partial class Form10 : Form
191 {
192 public Form8 mainForm;
193 public Form10()
194 {
195 InitializeComponent();
196 }
197 /// <summary>
198 /// 取消
199 /// </summary>
200 /// <param name="sender"></param>
201 /// <param name="e"></param>
202 private void btnCancel_Click(object sender, EventArgs e)
203 {
204 this.Close();
205 }
206 /// <summary>
207 /// 查找下一个
208 /// </summary>
209 /// <param name="sender"></param>
210 /// <param name="e"></param>
211 private void btnFindNext_Click(object sender, EventArgs e)
212 {
213 string source;
214 string finding;
215 if (this.checkBox1.Checked == false)
216 {
217 source = this.mainForm.textBox1.Text.ToLower();
218 finding = this.txtFindContent.Text.ToLower();
219 }
220 else
221 {
222 source = this.mainForm.textBox1.Text;
223 finding = this.txtFindContent.Text;
224 }
225
226 int temp = source.IndexOf(finding, mainForm.textBox1.SelectionStart + mainForm.textBox1.SelectedText.Length);
227 if (temp >= 0)
228 {
229 this.mainForm.textBox1.Select(temp, finding.Length);
230 mainForm.textBox1.ScrollToCaret();
231 this.mainForm.Focus();
232 }
233 else
234 {
235 MessageBox.Show("没有找到" + "'" + txtFindContent.Text + "'");
236 }
237 }
238 /// <summary>
239 /// 替换
240 /// </summary>
241 /// <param name="sender"></param>
242 /// <param name="e"></param>
243 private void btnReplace_Click(object sender, EventArgs e)
244 {
245 if (txtFindContent.Text == mainForm.textBox1.SelectedText)
246 {
247 mainForm.textBox1.SelectedText = txtReplace.Text;
248 }
249 else
250 {
251 btnFindNext.PerformClick();
252 }
253 }
254 /// <summary>
255 /// 全部替换
256 /// </summary>
257 /// <param name="sender"></param>
258 /// <param name="e"></param>
259 private void btnReplaceAll_Click(object sender, EventArgs e)
260 {
261 int count = 0;
262 int position;
263 string source;
264 string finding;
265 while (true)
266 {
267 //下面为查找代码
268 if (this.checkBox1.Checked == false)
269 {
270 source = this.mainForm.textBox1.Text.ToLower();
271 finding = this.txtFindContent.Text.ToLower();
272 }
273 else
274 {
275 source = this.mainForm.textBox1.Text;
276 finding = this.txtFindContent.Text;
277 }
278
279 if (count == 0)
280 {
281 position = source.IndexOf(finding, 0);
282 }
283 else
284 {
285 position = source.IndexOf(finding, mainForm.textBox1.SelectionStart + mainForm.textBox1.SelectedText.Length);
286 }
287
288 if (position >= 0)
289 {
290 this.mainForm.textBox1.Select(position, finding.Length);
291 mainForm.textBox1.ScrollToCaret();
292 this.mainForm.Focus();
293 count++;
294 }
295
296
297 //下面为替换代码
298 if (mainForm.textBox1.SelectedText.Length > 0)
299 {
300 btnReplace.PerformClick();
301 }
302 else
303 {
304 break;
305 }
306 }
307 MessageBox.Show("替换了" + count + "个地方");
308 }
309 /// <summary>
310 /// 表单初始化
311 /// </summary>
312 /// <param name="sender"></param>
313 /// <param name="e"></param>
314 private void Form10_Load(object sender, EventArgs e)
315 {
316 txtFindContent.Text = mainForm.textBox1.SelectedText;
317 }
318 }
319 }
二进制和内存流文件操作上机实验
往数据库放图片
school Myphoto
Pid id 自动增长类型 主码
Photo Image

1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Data.SqlClient;
6 using System.Drawing;
7 using System.Text;
8 using System.Windows.Forms;
9 using System.IO;
10
11 namespace WindowsApplication1
12 {
13 public partial class Form13 : Form
14 {
15 public Form13()
16 {
17 InitializeComponent();
18 }
19
20 SqlConnection connection;
21 /// <summary>
22 /// 打开数据库
23 /// </summary>
24 private void open()
25 {
26 string connstring = "Data Source=(local);Initial Catalog=school;User ID=sa";
27 connection = new SqlConnection(connstring);
28 connection.Open();
29 }
30 /// <summary>
31 /// 关闭数据库
32 /// </summary>
33 private void close()
34 {
35 connection.Dispose();
36 connection.Close();
37 connection = null;
38 }
39
40 /// <summary>
41 /// 输入SQL命令,得到DataReader对象
42 /// </summary>
43 public SqlDataReader GetDataReader(string sqlstring)
44 {
45 open();
46 SqlCommand mycom = new SqlCommand(sqlstring, connection);
47 SqlDataAdapter adapter = new SqlDataAdapter();
48 adapter.SelectCommand = mycom;
49 SqlDataReader Dr = mycom.ExecuteReader();
50 return Dr;
51
52 }
53
54 /// <summary>
55 /*******************************************************
56 **方 法 名:GetFileBytes
57 **输 入参数:Filename:文件名称;
58 **
59 **输 出参数:
60 **返 回 值:byte[]二进制流
61 **创 建 人:钱哨
62 **创 建日期:08-7-9
63 **描 述:将读取的文件转化成为二进制流。
64 *******************************************************/
65 /// <summary>
66 /// </summary>
67 /// <param name="Filename">打开的图片具体路径及文件名称</param>
68 /// <returns>比特流类型</returns>
69 public byte[] GetFileBytes(string Filename)
70 {
71 if (Filename == "")
72 return null;
73 try
74 {
75 FileStream fileStream = new FileStream(Filename, FileMode.Open, FileAccess.Read);
76 BinaryReader binaryReader = new BinaryReader(fileStream);
77
78 byte[] fileBytes = binaryReader.ReadBytes((int)fileStream.Length);
79 binaryReader.Close();
80 fileStream.Close();
81
82 return fileBytes;
83 }
84 catch
85 {
86 return null;
87 }
88 }
89 /// <summary>
90 /// 加载并刷新当前的combobox对象控件
91 /// </summary>
92 private void loadcombobox()
93 {
94 comboBox1.Items.Clear();
95 SqlDataReader dr = GetDataReader("select * from Myphoto");
96 while (dr.Read())
97 {
98 comboBox1.Items.Add(dr[0].ToString());
99 }
100 close();
101 }
102
103 /// <summary>
104 /// 初始化事件,加载combobox对象控件的列表信息
105 /// </summary>
106 /// <param name="sender"></param>
107 /// <param name="e"></param>
108 private void Form13_Load(object sender, EventArgs e)
109 {
110 loadcombobox();
111 }
112
113 /// <summary>
114 /// 打开图片
115 /// </summary>
116 /// <param name="sender"></param>
117 /// <param name="e"></param>
118 private void button1_Click(object sender, EventArgs e)
119 {
120 try
121 {
122 OpenFileDialog openfile = new OpenFileDialog();
123 openfile.Filter = "jpg类型图片(*.jpg)|*.jpg|BMP类型图片(*.bmp)|*.bmp";
124 if (openfile.ShowDialog() == DialogResult.OK)
125 {
126 byte[] picbinary = GetFileBytes(openfile.FileName);//第一步:打开图片文件,获得比特流
127 MemoryStream mempicstream = new MemoryStream(picbinary);//第二步:将比特流还存在内存工作流中。
128 pictureBox1.Image = Image.FromStream(mempicstream);//第三步:加载内存流到图片控件
129 textBox1.Text = openfile.FileName.ToString();
130 mempicstream.Dispose();
131 mempicstream.Close();
132 }
133 }
134 catch (Exception m)
135 {
136 MessageBox.Show("读取图片出错,可能的问题是:" + Convert.ToString(m), "错误提示");
137 }
138 }
139
140
141
142 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
143 {
144 if (comboBox1.SelectedIndex > -1)
145 {
146 string sqlstring = string.Format("select photo from Myphoto where pid="+comboBox1.Text);
147 SqlDataReader dr = GetDataReader(sqlstring);
148 if (dr.Read())
149 {
150 byte[] b = (byte[])dr["photo"];
151 MemoryStream ms = new MemoryStream(b);
152 //Image img = Image.FromStream(ms);
153 Image imge = new Bitmap(ms);
154 pictureBox1.Image = imge;
155 }
156 }
157 }
158 /// <summary>
159 /// 将打开的文件保存到数据库之中
160 /// </summary>
161 /// <param name="sender"></param>
162 /// <param name="e"></param>
163 private void button2_Click(object sender, EventArgs e)
164 {
165 try
166 {
167 if (pictureBox1.Image == null)
168 {
169 MessageBox.Show("禁止图片为空时候存储信息。", "错误提示");
170 }
171 else
172 {
173
174 MemoryStream ms = new MemoryStream();
175 Bitmap bm = new Bitmap(pictureBox1.Image);
176 bm.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
177 byte[] bytes = ms.ToArray();
178 //开始向数据库写信息
179 string insert = "INSERT INTO Myphoto(Photo) VALUES (@Photo)";
180 //sql命令参数
181 open();
182 SqlCommand sqlCommand = new SqlCommand(insert, connection);
183 //此句特别重要:指定SQL操作的参数性质!
184 sqlCommand.Parameters.Add("@Photo", SqlDbType.Binary).Value = bytes;
185
186 sqlCommand.ExecuteNonQuery();
187 close();
188
189 MessageBox.Show("另存图片成功", "提示");
190
191 ms.Dispose();
192 ms.Close();
193 bm.Dispose();
194 loadcombobox();
195 }
196
197 }
198 catch (Exception m)
199 {
200 MessageBox.Show("读取图片出错,可能的问题是:" + Convert.ToString(m), "错误提示");
201 }
202 }
203
204
205 }
206 }
来源:https://www.cnblogs.com/zhenqk/p/11101435.html
