File、Directory、Path是实际开发中应用频率比较高的类,程序对电脑的简单操作基本可以概括为对文件、目录、路径的操作,下面讲解主要用法:
File的用法
string filePath=@"d:\Instrument\guitar.txt";
string destinationFilePath=@"d:\Favorite\guitar.txt";
string moveFilePath=@"d:\Garbage\guitar.txt";
if (File.Exists(filePath))
{
Console.WriteLine("存在文件" + filePath);
}
else
{
//Create时,文件夹d:\Instrument必须存在,否则会报错
File.Create(filePath);
}
//Copy时,文件夹d:\Favorite必须存在,否则会报错
File.Copy(filePath, destinationFilePath, true);
//Move时,文件夹d:\Garbage必须存在,否则会报错
//Move时,如果moveFilePath值为d:\Garbage,
//那会创建一个名为Garbage的文件(没有后缀名)
File.Move(filePath, moveFilePath);
//Delete时没有目标文件不会报错
File.Delete(moveFilePath);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
Directory的用法
string directory=@"d:\Food\Meat";
string sourceDirName=@"d:\Music\Beyond";
string destDirName=@"d:\07\FavoriteMusic";
if (Directory.Exists(directory))
{
Console.WriteLine("目录" + directory + "存在");
}
else
{
//无论目录D:\Food是否存在,D:\Food\Meat都能成功创建
Directory.CreateDirectory(directory);
}
//Move指的是把D:\Music中的Beyond文件夹,移动到D:\07文件夹中,
//然后重命名为FavoriteMusic
//D:\07文件夹必须存在否则会报错
//如果D:\07中已经存在名为FavoriteMusic的文件夹那程序会报错
//Beyond文件夹中的文件或子目录在移动过后还会保持原样
//Move不能跨盘符移动
Directory.Move(sourceDirName, destDirName);
//只能删除空目录,包含文件或子目录都无法删除
Directory.Delete(@"d:\test");
//删除目录,及其文件和子目录
Directory.Delete(@"d:\test",true);
//搜索"e:\学习"目录下的所有txt文件,不搜索子目录
string[] files = Directory.GetFiles(@"e:\学习", "*.txt", SearchOption.TopDirectoryOnly);
//搜索"e:\学习"目录下的所有文件,搜索子目录
string[] allFiles = Directory.GetFiles(@"e:\学习", "*", SearchOption.AllDirectories);
//后边的两个参数可以不填,默认搜索顶层目录的所有文件
string[] normalFiles = Directory.GetFiles(@"e:\学习");
//搜索"e:\学习"目录下的所有名字中包含“课”的文件夹,不搜索子目录
string[] directories = Directory.GetDirectories(@"e:\学习", "*课*", SearchOption.TopDirectoryOnly);
//搜索"e:\学习"目录下的所有名字中包含“课”的文件夹,搜索子目录
string[] allDirectories = Directory.GetDirectories(@"e:\学习", "*", SearchOption.AllDirectories);
//后边的两个参数可以不填,默认搜索顶层目录的所有文件夹
string[] normalDirectories = Directory.GetDirectories(@"e:\学习");
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
Path的用法
string path =
@"d:\Entertainment\Music\在雨中.mp3";
//fullPath==@"d:\Name\guoguo"
string fullPath = Path.Combine(
@"d:\Name",
"guoguo");
//root==@"d:\"
string root = Path.GetPathRoot(path);
//@"d:\Entertainment\Music"
string directoryName = Path.GetDirectoryName(path);
//fileName="在雨中.mp3"
string fileName = Path.GetFileName(path);
//fileNameWithoutExtension="在雨中"
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path);
//extension=".mp3"
string extension = Path.GetExtension(path);
//newPath=@"d:\Entertainment\Music\在雨中.avi"
//path的值不会改变
string newPath = Path.ChangeExtension(path,
"avi");
//GetFullPath获取的是当前可执行程序的路径
//myFullPath=@"E:\Projects\20160725Share\20160725Share\bin\Debug\Data\text.txt"
string myFullPath = Path.GetFullPath(
@"Data\text.txt");
File
File的用法如下:
public void OperateFile()
{
//example文件初始内容截图如图一
string filePath = @"e:\Study\test\example.txt";
if (File.Exists(filePath))
{
//allText="蝈蝈first\r\n蝈蝈second\r\n蝈蝈third"
string allText =
File.ReadAllText(filePath,Encoding.Default);
//allLines[0]="蝈蝈first"
//allLines[1]="蝈蝈second"
//allLines[2]="蝈蝈third"
string[] allLines =
File.ReadAllLines(filePath,Encoding.Default);
byte[] allBytes = File.ReadAllBytes(filePath);
//byte[]转成string,
//str="蝈蝈first\r\n蝈蝈second\r\n蝈蝈third"
string str =
System.Text.Encoding.Default.GetString(allBytes);
//string类型转成byte[],
//byteArray={97,98,99,100,101,102}依次对应
//ASCII码表中a、b、c、d、e的十进制值
byte[] byteArray =
System.Text.Encoding.Default.GetBytes("abcde");
//example.txt中的内容是:abcde
File.WriteAllBytes(filePath, byteArray);
//example.txt中的内容是:
//"stringArray1\r\nstringArray2\r\nstringArray3",
//\r\n以换行的形式出现
File.WriteAllLines(filePath, new string[]
{ "stringArray1", "stringArray2", "stringArray3" });
//example.txt中的内容是:writeAllTxt的内容\r\n第二行,
//\r\n以换行的形式出现
File.WriteAllText(filePath, "writeAllTxt的内容\r\n第二行");
//AppendAllLines之后example文件内容截图如图二
File.AppendAllLines(filePath, new string[]
{ "appendFirst","appendSecond","appendThird"});
//AppendAllText之后example文件内容截图如图三
File.AppendAllText(filePath, "appendAllTextContent");
byte[] beforeAppendText = File.ReadAllBytes(filePath);
//AppendText之后example文件内容截图如图四
StreamWriter writer = File.AppendText(filePath);
writer.Write("streamWriterContent");
writer.Dispose();
byte[] afterAppendText = File.ReadAllBytes(filePath);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
图一
图二
图三
图四
FileStream
FileStream对象表示在磁盘或网络路径上指向文件的流。这个类提供了在文件中读写字节的方法,但经常使用StreamReader或StreamWriter执行这些功能。这是因为FileStream类操作的是字节和字节数组(不仅可以读写txt还能读写.mp3……),而Stream类操作的是字符数据(只能是文字)。
文件的访问方式(FileAccess),包括三个枚举:
FileAccess.Read(对文件读访问)
FileAccess.Write(对文件进行写操作)
FileAccess.ReadWrite(对文件读或写操作)
在FileStream构造函数不使用FileAccess枚举参数的版本中,使用默认值FileAccess. ReadWrite,即有文件的读写权限。
注意:
文件流使用结束后,一定要Close或Dispose,using(){}方法在使用完文件流对象后会自动将其释放
public void OperateFileStream()
{
string filePath=@"E:\Study\test\example.txt";
byte[] byteArray= new byte[1024];
using (FileStream sReader = new FileStream(filePath, FileMode.Open))
{
//length=32,汉字占2个字节、英文占1个字节2*6+5+6+5+2*2=32
int length = sReader.Read(byteArray, 0, byteArray.Length);
//result="蝈蝈first\r\n蝈蝈second\r\n蝈蝈third"
string result = System.Text.Encoding.Default.GetString(byteArray, 0, length);
//result="蝈蝈first\r\n蝈蝈second\r\n蝈蝈third\0\0\0\0\0......"
//"\0"指的是空字符
//byteArray的长度是1024数据不够1024byte时用"\0"填充
result = System.Text.Encoding.Default.GetString(byteArray);
}
using (FileStream sReader = new FileStream(filePath, FileMode.Open))
{
//sReader.Length=32
byte[] buffer = new byte[sReader.Length];
//length=32,汉字占2个字节、英文占1个字节2*6+5+6+5+2*2=32
int length = sReader.Read(buffer, 0, buffer.Length);
//result="蝈蝈first\r\n蝈蝈second\r\n蝈蝈third"
string result = System.Text.Encoding.Default.GetString(buffer, 0, length);
//result="蝈蝈first\r\n蝈蝈second\r\n蝈蝈third"
result = System.Text.Encoding.Default.GetString(buffer);
}
using (FileStream sWriter = new FileStream(filePath, FileMode.Create))
{
string content = "fileStream写入";
byte[] buffer = System.Text.Encoding.Default.GetBytes(content);
sWriter.Write(buffer, 0, buffer.Length);
//清空缓冲区,将缓冲区的数据写入到文件
sWriter.Flush();
//example文件中的内容变为"fileStream写入"
}
using (FileStream sAppender = new FileStream(filePath, FileMode.Append))
{
string content = "fileStream追加";
byte[] buffer = System.Text.Encoding.Default.GetBytes(content);
sAppender.Write(buffer, 0, buffer.Length);
//清空缓冲区,将缓冲区的数据写入到文件
sAppender.Flush();
//example文件中的内容变为"fileStream写入fileStream写入的内容fileStream追加"
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
StreamReader&StreamWriter
StreamReader实现了抽象基类TextReader,而StreamWriter实现了抽象基类TextWriter,两者分别用于对流的读取与写入。
StreamReader类:
1、公共属性
BaseStream 返回基础流。
CurrentEncoding 获取当前 StreamReader 对象正在使用的当前字符编码。
EndOfStream 获取一个值,该值表示当前的流位置是否在流的末尾。
- 1
- 2
- 3
2、公共方法
Close, 关闭 StreamReader 对象和基础流,并释放与读取器关联的所有系统资源。 (重写 TextReader..::.Close()()()。)
CreateObjRef, 创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。 (继承自 MarshalByRefObject。)
DiscardBufferedData, 允许 StreamReader 对象丢弃其当前数据。
Dispose 已重载。
GetLifetimeService, 检索控制此实例的生存期策略的当前生存期服务对象。 (继承自 MarshalByRefObject。)
InitializeLifetimeService, 获取控制此实例的生存期策略的生存期服务对象。 (继承自 MarshalByRefObject。)
MemberwiseClone, 已重载。
Peek, 返回下一个可用的字符,但不使用它。 (重写 TextReader..::.Peek()()()。)
Read, 已重载。 读取输入流中的下一个字符或下一组字符。
ReadBlock, 从当前流中读取最大 count 的字符并从 index 开始将该数据写入 buffer。 (继承自 TextReader。)
ReadLine, 从当前流中读取一行字符并将数据作为字符串返回。 (重写 TextReader..::.ReadLine()()()。)
ReadToEnd, 从流的当前位置到末尾读取流。 (重写 TextReader..::.ReadToEnd()()()。)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
StreamReader实例代码如下:
public void OperateStream()
{
string filePath = @"e:\Study\test\example.txt";
string errorMsg = string.Empty;
string msg=string.Empty;
try
{
//生成StreamReader实例对象,方法一
StreamReader sReader = new StreamReader(filePath);
//成StreamReader实例对象,方法二
//FileStream fileStream = new FileStream(filePath, FileMode.Open);
//StreamReader sReaderFromFileStream = new StreamReader(fileStream);
//每次只读一行
msg = sReader.ReadLine();
while (msg!=null)
{
Console.WriteLine("msg=" + msg);
msg = sReader.ReadLine();
}
sReader.Close();
sReader = new StreamReader(filePath);
//EndOfStream判断当前的流位置是否在流的末尾
//如果文件中没有内容,EndOfStream为true
while (!sReader.EndOfStream)
{
//每次只读一行
msg = sReader.ReadLine();
Console.WriteLine("msg=" + msg);
}
sReader.Close();
sReader = new StreamReader(filePath);
//EndOfStream判断当前的流位置是否在流的末尾
//如果文件中没有内容,EndOfStream为true
while (!sReader.EndOfStream)
{
//读取文件中所有内容
//此处为:蝈蝈first\r\n蝈蝈second\r\n蝈蝈third
msg = sReader.ReadToEnd();
Console.WriteLine("msg=" + msg);
}
sReader.Close();
}
catch (Exception ex)
{
errorMsg = ex.Message;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
StreamWriter实例代码如下:
public void OperateStream()
{
string filePath = @"e:\Study\test\example.txt";
string errorMsg = string.Empty;
string msg=string.Empty;
try
{
//生成StreamWriter实例对象,方法一
StreamWriter sWriter = new StreamWriter(filePath);
//生成StreamWriter实例对象,方法二
//FileStream fileStream = new FileStream(filePath, FileMode.Create);
//StreamWriter sWriterFromFileStream = new StreamWriter(fileStream);
//会替换原有内容
sWriter.Write("Write内容");
sWriter.Close();
sWriter = new StreamWriter(filePath);
//会替换原有内容
sWriter.WriteLine("WriteLine内容");
sWriter.Close();
}
catch (Exception ex)
{
errorMsg = ex.Message;
}
try
{
//生成StreamWriter追加内容实例对象,方法一
StreamWriter sAppender = new StreamWriter(filePath, true);
//生成StreamWriter追加内容实例对象,方法二
//FileStream fileStream = new FileStream(filePath, FileMode.Append);
//StreamWriter sAppenderFromFileStream = new StreamWriter(fileStream);
sAppender.Write("追加Write内容1");
sAppender.Write("追加Write内容2");
//WriteLine会在内容之后加上"\r\n"
sAppender.WriteLine("追加WriteLine内容001");
sAppender.WriteLine("追加WriteLine内容002");
sAppender.Write("追加Write内容3");
//追加后文件截图如下
sAppender.Close();
}
catch (Exception ex)
{
errorMsg = ex.Message;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19