重温一下C#中File类的一些基本操作:

File类,是一个静态类,主要是来提供一些函数库用的。

使用时需要引入System.IO命名空间。

一、常用操作:

1、创建文件方法

//参数1:要创建的文件路径

File.Create(@"D:\Test\Debug1\测试.txt")

2、打开文件方法

//参数1:要打开的文件路径,参数2:打开的文件方式

File.Open(@"D:\Test\Debug1\测试.txt",FileMode.Append)

3、追加文件方法

//参数1:要追加的文件路径,参数2:追加的内容

File.AppendAllText(@"D:\Test\Debug1\测试.txt","哈哈");

4、复制文件方法

//参数1:要复制的源文件路径,参数2:复制后的目标文件路径,参数3:是否覆盖相同文件名
 File.Copy(@"D:\Test\Debug1\测试.txt", @"D:\Test\Debug2\测试1.txt", true);

5、移动文件方法

//参数1:要移动的源文件路径,参数2:移动后的目标文件路径
File.Move(@"D:\Test\Debug1\测试.txt", @"D:\Test\Debug3\测试2.txt");

6、删除文件方法

//参数1:要删除的文件路径
 File.Delete(@"D:\Test\Debug1\测试.txt");

7、设置文件属性方法

//参数1:要设置属性的文件路径,参数2:设置的属性类型(只读、隐藏等)
File.SetAttributes(@"D:\Test\Debug1\测试.txt", FileAttributes.Hidden);

二、读写操作:

当读取的文件内容不多时:

  • File.ReadAllText(FilePath)
  • File.ReadAllText(FilePath, Encoding)
  • File.ReadAllLines(FilePath)

例如:

  • string str = File.ReadAllText(@"c:\temp\ascii.txt");
  • string str2 = File.ReadAllText(@"c:\temp\ascii.txt", Encoding.ASCII);
  • string[] strs = File.ReadAllLines(@"c:\temp\ascii.txt");

读取内容比较多时:使用StreamReader类

初始化:

  • StreamReader sr1 = new StreamReader(@"c:\temp\utf-8.txt");
  • StreamReader sr2 = new StreamReader(@"c:\temp\utf-8.txt", Encoding.UTF8);
  • FileStream fs = new FileStream(@"C:\temp\utf-8.txt", FileMode.Open, FileAccess.Read, FileShare.None);
  • StreamReader sr3 = new StreamReader(fs);
  • StreamReader sr4 = new StreamReader(fs, Encoding.UTF8);

初始化后:

读一行

  • string nextLine = sr.ReadLine();

读一个字符

  • int nextChar = sr.Read();

读100个字符

  • int nChars = 100;
  • char[] charArray = new char[nChars];
  • int nCharsRead = sr.Read(charArray, 0, nChars);

全部读完

  • string restOfStream = sr.ReadToEnd();

使用完StreamReader之后,不要忘记关闭它:

  • sr.Closee();

写的内容不多时候

  • string str1 = "Good Morning!";
  • File.WriteAllText(@"c:\temp\test\ascii.txt", str1);
  • string[] strs = { "Good Morning!", "Good Afternoon!" };
  • File.WriteAllLines(@"c:\temp\ascii.txt", strs);

写的内容比较多时使用StreamWriter

如果文件不存在,创建文件; 如果存在,覆盖文件

  • StreamWriter sw1 = new StreamWriter(@"c:\temp\utf-8.txt");
  • FileStream fs = new FileStream(@"C:\temp\utf-8.txt", FileMode.CreateNew, FileAccess.Write, FileShare.Read);
  • StreamWriter sw3 = new StreamWriter(fs);

如果文件不存在,创建文件; 如果存在,覆盖文件

  • FileInfo myFile = new FileInfo(@"C:\temp\utf-8.txt");
  • StreamWriter sw5 = myFile.CreateText();

初始化完成后,可以用StreamWriter对象一次写入一行,一个字符,一个字符数组,甚至一个字符数组的一部分。

写一个字符

  • sw.Write('a');

写一个字符数组

  • char[] charArray = new char[100];
  • sw.Write(charArray);

写一个字符数组的一部分

  • sw.Write(charArray, 10, 15);

同样,StreamWriter对象使用完后,不要忘记关闭。

  • sw.Close();

=================================================================

接下来是一个简单的控制台应用程序的源码

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO; namespace _033_test
{
class Program
{
static void Main(string[] args)
{
FileManager file = new FileManager();
file.MenuChoice(); Console.ReadKey();
}
} class FileManager
{
public void DisPlayer()
{
Console.WriteLine("============File Management System=============");
Console.WriteLine("1.Create 2.Delete 3.Check 4.Revise");
Console.WriteLine("===============================================");
Console.WriteLine("请输入你要进行的操作编号,中途如要返回上一级请输入exit");
} public void MenuChoice()
{
while (true)
{
DisPlayer();
string choice = Console.ReadLine();
switch (choice)
{
case "": Create(); continue;
case "": Delete(); continue;
case "": Check(); continue;
case "": Revise(); continue;
case "exit": return;
default: Console.WriteLine("请重新输入正确的选项"); break;
}
}
} public void Create()
{
Console.WriteLine("请指定路径:");
while (true)
{
string path = Console.ReadLine();
if (path == "exit")
{
Console.WriteLine("返回上一级");
break;
}
try
{
if (File.Exists(path))
{
Console.WriteLine("是否覆盖原文件?Y/N");
string str = Console.ReadLine();
if (str == "y" || str == "Y")
{
File.Create(path).Close();
Console.WriteLine("已覆盖原文件");
break;
}
else
{
Console.WriteLine("放弃覆盖,请重新输入路径");
continue;
}
}
else
{
File.Create(path).Close();
Console.WriteLine("文件已创建");
break;
}
}
catch (Exception)
{
Console.WriteLine("错误路径,请重新输入");
continue;
}
}
} public void Delete()
{
Console.WriteLine("请指定路径:");
while (true)
{
string path = Console.ReadLine();
if (path == "exit")
{
Console.WriteLine("返回上一级");
break;
}
if (File.Exists(path))
{
File.Delete(path);
Console.WriteLine("文件已删除");
break;
}
else
{
Console.WriteLine("不存在该文件,请重新输入路径");
continue;
}
}
} public void Check()
{
Console.WriteLine("请指定路径:");
while (true)
{
string path = Console.ReadLine();
if (path == "exit")
{
Console.WriteLine("返回上一级");
break;
}
if (File.Exists(path))
{
FileInfo fInfo = new FileInfo(path);
Console.WriteLine("1.查看文件信息 2.查看文件内容");
while (true)
{
string str = Console.ReadLine();
switch (str)
{
case "":
Console.WriteLine("文件名:" + fInfo.Name);
Console.WriteLine("创建时间:" + fInfo.CreationTime);
Console.WriteLine("最后修改时间:" + fInfo.LastWriteTime);
Console.WriteLine("字节大小:" + fInfo.Length);
break;
case "":
string type = Path.GetExtension(path);
if (type == ".doc" || type == ".txt")
{
byte[] brr = File.ReadAllBytes(path);
string value = Encoding.Default.GetString(brr, , brr.Length);
Console.WriteLine(value);
}
else
{
Console.WriteLine("该类型文件不支持查看");
}
break;
default: Console.WriteLine("错误指令,请重新输入:"); continue;
}
break;
}
break;
}
else
{
Console.WriteLine("不存在该文件,请重新输入路径");
continue;
}
}
} public void Revise()
{
Console.WriteLine("请指定路径:");
while (true)
{
string path = Console.ReadLine();
if (path == "exit")
{
Console.WriteLine("返回上一级");
break;
}
if (File.Exists(path))
{
Console.WriteLine("1.修改内容 2.修改文件名 3.文末添加");
while (true)
{
string str = Console.ReadLine();
switch (str)
{
case "":
Console.WriteLine("本功能允许你将某个字符串替换成另一个字符");
string type = Path.GetExtension(path);
if (type == ".doc" || type == ".txt")
{
byte[] brr = File.ReadAllBytes(path);
string value = Encoding.Default.GetString(brr, , brr.Length);
Console.WriteLine("请输入你要修改的字符串,若文件中有该字符,将全部替换");
string str2 = Console.ReadLine();
Console.WriteLine("请输入将要修改为的字符串");
string str3 = Console.ReadLine();
byte[] brr2 = Encoding.Default.GetBytes(value.Replace(str2, str3));
File.WriteAllBytes(path, brr2);
}
else
{
Console.WriteLine("该类型文件不支持修改");
}
break;
case "":
FileInfo f = new FileInfo(path);
while (true)
{
try
{
Console.WriteLine("请输入文件名(不需要输入拓展名和路径)");
string fName = Console.ReadLine();
//获取文件的父目录和拓展名,并加在fname两边,使其做到重命名的效果
File.Move(path, f.Directory + "\\" + fName + Path.GetExtension(path));
Console.WriteLine("已将该文件重命名");
}
catch (Exception) {
Console.WriteLine("文件名出错,重新输入!");
continue;
}
break;
}
break;
case "":
Console.WriteLine("请输入内容,回车换行,exit退出");
FileStream fs = new FileStream(path, FileMode.Append);
while (true)
{
string value = Console.ReadLine();
if (value == "exit") break;
byte[] arr = Encoding.Default.GetBytes(value + "\r\n");
fs.Write(arr, , arr.Length);
fs.Flush();
}
fs.Close();
break;
default: Console.WriteLine("错误指令,请重新输入:"); continue;
}
break;
}
break;
}
else
{
Console.WriteLine("不存在该文件,请重新输入路径");
continue;
}
}
}
} }

FileManager

运行结果:

参考来源:https://www.cnblogs.com/xielong/p/6187308.htmlhttps://www.cnblogs.com/Herzog3/p/5090974.html

最新文章

  1. [LintCode] Maximum Depth of Binary Tree 二叉树的最大深度
  2. 6/8/9/10/11 Sprint2 看板和燃尽图
  3. 基于WebView的混合编程
  4. php网页切图/js切图
  5. (转)SqlServer将数据库中的表复制到另一个数据库
  6. BZOJ 1657 奶牛的歌声
  7. kali linux 一些工具及命令集1(搜集DNS信息)
  8. insertAfter()
  9. DirectX 3D 之C#开发
  10. [转]JSON.stringify 语法实例讲解
  11. cf B Inna and Candy Boxes
  12. 光学字符识别OCR
  13. socket传输数据循环多次的性能要好于一次
  14. 对国内AR产业的预言
  15. 第一册:lesson thirty one。
  16. 微服务之consul
  17. IDEA下Spring Boot显示Run Dashboard面板
  18. mybatis {arg0} 与 {0}
  19. CSS中text-shadow的几个好看的文字demo及其代码
  20. 【 D3.js 入门系列 — 11 】 入门总结

热门文章

  1. vue cli 3.0创建项目
  2. abap test seam 和 TEST-INJECTION
  3. mysql千万级大数据SQL查询优化30条经验
  4. web前端设计最好用的工具
  5. log4j2教程【RollingFileAppender】
  6. 选择排序java实现
  7. ABP入门系列之1——ABP总体介绍
  8. 1344:【例4-4】最小花费 dijkstra
  9. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'catchFromPBomService': Cannot create inner bean '(inner bean)#302efb82' of type [com.thinkgem.jeesite.modules.fd
  10. python的oop概述