c#i\o接口

Directory类和Directoryinfo'类专门用来操作目录(文件夹)信息,区别是directory类是静态类

directory.getfiles拿某个目录下的文件,返回值是string[],

directoryinfo.getfiles拿某个文件下的文件返回值是fileinfo[]

directory.delete删除目录;

directory.createdirectory创建目录

directory.enumeratedirectories拿到某个目录下面的子目录;directory.getparent(path)父目录

directory.exists判断某个目录是否存在,返回值是布尔值;

directory.getcurrentdirectory拿到某个目录的常用信息,程序运行的当前目录;

directory获取name.fullname不方便,所以 使用directoryinfo类

实例化directoryinfo类

directory.getcreationtime创建时间;directory.getlastwritetime()最后一次修改时间;dirextory.getlastsccesstime()最后一次访问时间.

directory.move()移动目录不能跨盘符,切移动目录必须存在.

string[] files = Directory.GetFiles("F:\\dfile");
            foreach (string file in files)
            {
                Console.WriteLine(file);
            }
            DirectoryInfo di = new DirectoryInfo(path1);
            FileInfo[] Fi = di.GetFiles();
            foreach (var item in Fi)
            {
                Console.WriteLine(item);
            }
            try
            {
                DirectoryInfo dif = new DirectoryInfo("F:\\c");
                // Directory.Delete("F:\\c");
               // dif.Create();
                dif.Delete();
              // DirectoryInfo info=Directory.CreateDirectory("F:\\c");

            }
            catch (Exception)
            {

                Console.WriteLine("文件存在");
            }
            Directory.GetCurrentDirectory();
            Console.WriteLine(Directory.GetCurrentDirectory());

driveinfo需实例化

driveinfo.name盘符;driveinfo.totalsize盘符空间大小;driveinfo.availablefreespace可用空间;driveinfo.volumelable盘符标签;driveinfo.driveformat盘符格式.

path类

ispathrooted(path)指示文件路径包含根返回布尔值.hasextension(path)路径返回布尔值(重要)

changeextension()改变文件的后缀名.

path.combine(path)合并多个路径,path.join合并多个路径,combine是指路径的合并,join是指字符串的拼接.

Path.Exists()不存在此方法。  Directory目录类, File类
/Directory.Exists()即可以判断文件路径是否存在,也可以判断目录路径是否存在。
 File.Exists()只能判断文件路径是否存在。


// 合并多个路径(重要)
var path4 = @"C:\Program Files\";
var path5 = @"Utilities\SystemUtilities";
Console.WriteLine(Path.Join(path4, path5));

string[] pathss = { @"C:\Program Files\", @"Utilities\SystemUtilities" };
Console.WriteLine(Path.Join(pathss));

// Join()和Combine()区别:join是字符串拼接,combine才是合并(功能强)  (重要)
string path6 = "C:/Users/Public/Documents/";
string path7 = "C:/Users/User1/Documents/Financial/";
Console.WriteLine(Path.Join(path6, path7));
Console.WriteLine(Path.Combine(path6, path7));


// 判断目录是否存在。(重要)
Console.WriteLine("---------------------");
// Path.Exists()不存在此方法。  Directory目录类, File类
// Directory.Exists()即可以判断文件路径是否存在,也可以判断目录路径是否存在。
// File.Exists()只能判断文件路径是否存在。
Console.WriteLine(Directory.Exists("C:\\inetpub\\a.txt")); // false
Console.WriteLine(Directory.Exists("C:\\inetpub")); // true
Console.WriteLine(File.Exists("C:\\inetpub\\a.txt")); // false
Console.WriteLine(File.Exists("C:\\inetpub")); // false
Console.WriteLine("---------------------");

// 获取目录名字;获取文件后缀名称;获取文件名;获取完整路径;(重要)
string filePath = @"C:\MyDir\MySubDir\myfile.ext";
Console.WriteLine($"目录名字:{Path.GetDirectoryName(filePath)}");
Console.WriteLine($"文件后缀名:{Path.GetExtension(filePath)}");
Console.WriteLine($"文件名:{Path.GetFileName(filePath)}");
Console.WriteLine($"文件名(不带后缀):{Path.GetFileNameWithoutExtension(filePath)}");
Console.WriteLine($"完整路径:{Path.GetFullPath(filePath)}");
Console.WriteLine("---------------------");


// Invalid非法
char[] chars = Path.GetInvalidFileNameChars();
for (int i = 0; i < chars.Length; i++)
{
    char someChar = chars[i];
    if (char.IsWhiteSpace(someChar))
    {
        // \t===tab键,X4
        Console.WriteLine(",\t{0:X4}", (int)someChar);
    }
    else
    {
        // (重要)标准格式说明符:https://learn.microsoft.com/zh-cn/dotnet/standard/base-types/standard-numeric-format-strings
        Console.WriteLine("{0:c},\t{1:X4}", someChar, (int)someChar);
    }
}

Console.WriteLine("---------------------");
// Random随机
string result1 = Path.GetRandomFileName();
Console.WriteLine("随机产生一个文件名:" + result1);

Console.WriteLine("---------------------");
// 了解,不用管。
// 应用程序所在目录: C:\Users\dong\Desktop\上位机\18\ConsoleApp1\ConsoleApp1\bin\Debug\net6.0
string relativeTo = "drivers";
string path = "C:\\Users\\dong\\Desktop\\上位机\\18\\ConsoleApp1\\ConsoleApp1\\bin\\Debug\\net6.0";
Console.WriteLine(Path.GetRelativePath(relativeTo, path));
file类
 讲解File类:提供用于创建、复制、删除、移动、替换和打开单一文件的静态方法

string path = @"C:\Users\dong\Desktop\上位机\18\ConsoleApp1\ConsoleApp3\bin\Debug\net6.0\log.txt";
if (!File.Exists(path)) // 判断文件是否已经存在。
{
    // StreamWriter写文件流。
    // File.CreateText()创建文件。
    using (StreamWriter sw = File.CreateText(path)) // using语句会自动关闭文件流。
    {
        // sw.WriteLine()写到path路径下的文件中
        sw.WriteLine("Hello"); // Console.WriteLine()写到命令行窗口
        sw.WriteLine("And");
        sw.WriteLine("Welcome");
    }
}

string path2 = @"C:\Users\dong\Desktop\上位机\18\ConsoleApp1\ConsoleApp3\bin\Debug\net6.0\log2.txt";
if (!File.Exists(path2)) {
    //  File.AppendText()会在文件中追加内容。
    // 没有使用using子句,需要开发者人为的关闭流。
    StreamWriter sw1 = File.CreateText(path2);
    sw1.WriteLine("你好");
    sw1.WriteLine("欢迎您");
    sw1.Close();
}


// StreamReader读文件流; File.OpenText()打开一个文件
using (StreamReader sr = File.OpenText(path))
{
    string s; // 保存结果
    // sr.ReadLine()读取一行,如果有结果,才打印
    while ((s = sr.ReadLine()) != null)
    {
        Console.WriteLine(s);
    }
}

// 把读取的结果合并到一行再打印。
using (StreamReader sr = File.OpenText(path2))
{
    string s = string.Empty; // 保存结果一行的结果 
    string result = ""; // 保存所有行的结果 
    while ((s = sr.ReadLine()) != null)
    {
        result += s;
    }
    Console.WriteLine(result);
}

// 删除aa.txt,删除的文件如何不存在,不会报异常。
File.Delete("D:\\a1.txt");


// 复制文件
string destPath1 = "D:\\log1.txt";
if (File.Exists(destPath1))
{
    File.Delete(destPath1);
    File.Copy(path2, destPath1);
}
else
{
    File.Copy(path2, destPath1);
}


// 建议写如下的代码风格。
string destPath = "D:\\log2.txt";
if (File.Exists(destPath)) // 目标路径如果存在,需要先删除,再复制。
{
    File.Delete(destPath);
}
File.Copy(path2, destPath);

// 移动文件,特别提醒:移动文件时可以重命名。
string oldPath = "D:\\a2.txt";
string destPath2 = "E:\\log3.txt";
if (File.Exists(destPath2))
{
    File.Delete(destPath2);
}
if (File.Exists(oldPath)) {
    File.Move(oldPath, destPath2);
}


// 创建文件Create()返回FileStream,CreateText()返回的是StreamWriter
// FileStream即可以读取文件,又可以向文件中写入数据。FileStream=StreamWriter+StreamRead
string path3 = "D:\\a3.txt";
using (FileStream fs = File.Create(path3))
{
    // 字节数组===字节流  UTF8Encoding()负责编码。
    byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.你好");
    fs.Write(info, 0, info.Length); // 写入的是字符流,而FileStream中的WriteLine()写的是字符串。
}

//  File.Open()打开文件。注意:FileMode.png
using (FileStream fs = File.Open(path3, FileMode.Open))
{
    byte[] b = new byte[1024];
    UTF8Encoding temp = new UTF8Encoding(true);

    // fs.Read()读文件。
    // fs.Read()读取是字节流,返回值是整形数字,数字表示文件读取的位置
    while (fs.Read(b, 0, b.Length) > 0)
    {
        // GetString()把字节流转换成字符串
        Console.WriteLine(temp.GetString(b));
    }
}

// 替换文件
string oldFile = "D:\\a.txt";
string newFile = "d:\\b.txt";
string bakFile = "d:\\b.bak.txt";

// 替换之前,新文件必须存在
if (!File.Exists(newFile)) {
    using (StreamWriter sw = File.CreateText(newFile))
    {
        sw.WriteLine("aaa");
    }
}
if(File.Exists(oldFile))
{
    File.Replace(oldFile, newFile, bakFile);
}


using (FileStream fs = File.OpenWrite(bakFile))
{
    // String==string, Byte==byte, Boolean=boolean
    byte[] info =
        new UTF8Encoding(true).GetBytes("This is to test the OpenWrite method.");

    // Add some information to the file.
    fs.Write(info, 0, info.Length);
}

// 加密及解密(了解)
File.Encrypt(newFile);
//File.Decrypt(newFile);
//File.Decrypt(bakFile);

using (FileStream fs = File.OpenRead(newFile))
{
    byte[] b = new byte[1024];
    UTF8Encoding temp = new UTF8Encoding(true);

    while (fs.Read(b, 0, b.Length) > 0)
    {
        Console.WriteLine(temp.GetString(b));
    }
}
// FileStream类  Stream流====理解水流,在语言里面是二进制流。
// FileStream类,即可以读文件,也可写文件。
// StreamReader类,主要负责读取文件的。
// StreamWriter类,主要负责写文件的。
// 所以,你可以这样认为:FileStream类 = StreamReader类 + StreamWriter类

// 通过FileStream实例化,也可以读取文件,但没有使用File和FileInfo方便。
/*string pathSource = "D:\\c.txt";
string pathNew = "D:\\d.txt";
using (FileStream fsSource = new FileStream(pathSource, FileMode.OpenOrCreate, FileAccess.Read))
{
    // 根据流的长度定义字节数组,字节数组用来保存读取的数据。
    byte[] bytes = new byte[fsSource.Length];

    // 以下两个变量为fsSource.Read()做准备的。
    int numBytesToRead = (int)fsSource.Length; // 读取的数据长度
    int numBytesRead = 0; // 偏移量,读取的位置

    while (numBytesToRead > 0) // 文件中有数据。
    {
        // 开始读文件,逐个字符读取。
        int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);

        // Break when the end of the file is reached.
        if (n == 0) // 文件读完了。
            break;

        numBytesRead += n;
        numBytesToRead -= n;
    }
    numBytesToRead = bytes.Length;

    Console.WriteLine(new UTF8Encoding(true).GetString(bytes));

    // Write the byte array to the other FileStream.
    using (FileStream fsNew = new FileStream(pathNew,FileMode.OpenOrCreate, FileAccess.Write))
    {
        fsNew.Write(bytes, 0, numBytesToRead);
    }
}*/

// 用StreamReader类 + StreamWriter类把上面业务逻辑重写。
string pathSource = "D:\\c.txt";
string pathNew = "D:\\d.txt";
using (StreamReader sr = new StreamReader(pathSource))
{
    // ReadToEnd()从头读到尾
    string content = sr.ReadToEnd();
    Console.WriteLine(content);

    using (StreamWriter sw = new StreamWriter(pathNew))
    {
        sw.WriteLine(content);
    }

}

// 解决一下操作文件时,如何排除错误?仔细阅读异常信息。
/*using (FileStream fsSource = new FileStream("D:\\e.txt", FileMode.Open, FileAccess.Read)) { 

}*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玉玊则不达

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值