重温一下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

C#File类常用文件操作以及一个模拟的控制台文件管理系统的更多相关文章

  1. C#File类常用的文件操作方法(创建、移动、删除、复制等)

    File类,是一个静态类,主要是来提供一些函数库用的.静态实用类,提供了很多静态的方法,支持对文件的基本操作,包括创建,拷贝,移动,删除和 打开一个文件. File类方法的参量很多时候都是路径path ...

  2. File类常用的方法与字节流类方法简介

    File类常用的方法 获取功能的方法 public String getAbsolutePath() :返回此File的绝对路径名字符串. public String getPath() :将此Fil ...

  3. 关于Properties类常用的操作

    import java.io.*;import java.util.Enumeration;import java.util.Properties;/** * 关于Properties类常用的操作 * ...

  4. 重新想象 Windows 8 Store Apps (24) - 文件系统: Application Data 中的文件操作, Package 中的文件操作, 可移动存储中的文件操作

    原文:重新想象 Windows 8 Store Apps (24) - 文件系统: Application Data 中的文件操作, Package 中的文件操作, 可移动存储中的文件操作 [源码下载 ...

  5. Java基础---Java---IO流-----File 类、递归、删除一个带内容的目录、列出指定目录下文件夹、FilenameFilte

    File 类 用来将文件或者文件夹封装成对象 方便对文件与文件夹进行操作. File对象可以作为参数传递给流的构造函数 流只用操作数据,而封装数据的文件只能用File类 File类常见方法: 1.创建 ...

  6. IO流--字符流与字节流--File类常用功能

    IO流的常用方法: 1: 文件的读取和写入图解: 2:字节流: 读写文件的方法: 一般效率读取: 读取文件:        FileInputStream(); 写数据:            Fil ...

  7. 利用File类过滤器列出目录下的指定目录或文件

    需求:列出d盘下的全部txt文件 实现方法:利用File类的过滤器功能 package com.test.common.util; import java.io.File; import java.i ...

  8. 笔记13:File 类的一些操作

    一.对文件的创建(create) private void button1_Click(object sender, EventArgs e) { File.Create(@"F:\\QQP ...

  9. C++文件操作(输入输出、格式控制、文件打开模式、测试流状态、二进制读写)

    1.向文件写数据 头文件#include <ofstream> ①Create an instance of ofstream(创建ofstream实例) ②Open the file w ...

随机推荐

  1. 怎么eclipse或MyEclipse中添加javaSe的源码

    怎么eclipse或MyEclipse中添加javaSe的源码 有时在eclipse里我们调用java提供给我们的方法,我们有时需要查看java提供给我们的调用方法的源码或java提供给我们的核心类的 ...

  2. vs code中文扩展包

    vs code 中文拓展安装失败时,可以手动下载安装,下载对版本的中文包. https://marketplace.visualstudio.com/_apis/public/gallery/publ ...

  3. 【LeetCode每天一题】Add Binary(二进制加法)

    Given two binary strings, return their sum (also a binary string).The input strings are both non-emp ...

  4. libcurl.a 跨平台

    编译成libxxx.a文件后, 通过lipo把多个不同架构的文件合并起来成为一个文件 在build setting 设置  head search path , library search path ...

  5. vue二、脚手架搭建

    1:安装nodeJs(下载一路回车) https://nodejs.org/zh-cn/ 2:检验nodeJs是否安装成功 (注意nodeJs是否添加到window路径中) 进入cmd -> n ...

  6. MySQL实用基本操作

    本博客写是装好Mysql并配好环境变量后的基本操作(windows10系统下)且都是黑框内的操作. 一.登陆MySQL 首先启动服务,在桌面左下角图标处点击右键Windows PowerShell(管 ...

  7. day16 python之匿名函数,递归函数

    匿名函数 匿名函数格式 函数名 = lambda 参数 :返回值 #参数可以有多个,用逗号隔开 #匿名函数不管逻辑多复杂,只能写一行,且逻辑执行结束后的内容就是返回值 #返回值和正常的函数一样可以是任 ...

  8. audio google play()

    <audio id="music" src="" preload loop="loop" autostart="true&q ...

  9. Log4j2 简介

    介绍 Log4j2是Log4j的升级版,与之前的版本Log4j 1.x相比.有重大的改进,修正了Logback固有的架构问题的同事,改进了许多Logback所具有的功能. 特性 一.API 分离 Lo ...

  10. ts --基础类型

    声明js的基本类型1.数字let a: number = 2; 2.字符串let aa: string = "22" 3.数组 (1) 数组元素: let b: number[] ...