C# 文件读写 IO.FileInfo

/// 参考链接  https://learn.microsoft.com/zh-cn/dotnet/api/system.io.fileinfo?view=net-8.0
// 需要直到的是 fileinfo 主要用于查看文件信息, 搭配FileStream或StreamWrite可以操作文件IO, FileStream 需要实例化, 可以接受fileinfo的对象

using Microsoft.VisualBasic;
using System;
using System.Buffers.Text;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Text;  // Compression 可以读写压缩文件

namespace ConsoleApp_FileIn_Out
{

    internal class Program
    {
        static void Main(string[] args)
        {
            // fileinfos();     // 文件信息
            // readwritefiles();     // 读写文件
            // write_read_files();   // 读写文件 方式2
            // textfile();           // 创建空文件并读取文件
            // Copys();         // 复制文件
            // newfile();       // 新建文件
            // newSymbol();        // 创建符号链接
            // writeNew();      // 新建文件并写入
            // Moves();         // 移动文件
            // Refresh();          // 刷新文件
            // ReplaceFile("d:/1.txt", "123", "OK");  // 修改文件内容并保存为.rew新文件
            Console.ReadKey();

        }


        // 获取文件信息
        static void fileinfos()
        {
            FileInfo fileinfo = new FileInfo("d:/天翼云盘下载/LINQPad_jb51.rar");
            var M = Convert.ToInt32(fileinfo.Length);  // 输出文件大小, 返回string类型, 默认为大小为(B)字节
            // 1KB (Kilobyte 千字节)=1024B,
            // 1MB(Megabyte 兆字节 简称“兆”) = 1024KB,

            Console.WriteLine("文件最后访问时间: " + fileinfo.LastAccessTime);  // 文件最后访问时间
            Console.WriteLine("文件最后写入时间: " + fileinfo.LastWriteTime);   // 文件最后写入时间
            Console.WriteLine("获取或设置当前文件或目录的创建时间: " + fileinfo.CreationTime);    // 获取或设置当前文件或目录的创建时间。
            Console.WriteLine("文件格式类型: " + fileinfo.Extension);       // 文件格式类型
            Console.WriteLine("获取或设置确定当前文件是否为只读的值: " + fileinfo.IsReadOnly);      // 获取或设置确定当前文件是否为只读的值。

            Console.WriteLine("获取指示文件是否存在值: " + fileinfo.Exists);          // 获取指示文件是否存在值。
            Console.WriteLine("获取父目录的实例: " + fileinfo.Directory);       // 获取父目录的实例。
            Console.WriteLine("获取表示目录的完整路径的字符串: " + fileinfo.DirectoryName);   // 获取表示目录的完整路径的字符串。

            Console.WriteLine("获取文件名称: " + fileinfo.Name);            // 获取文件名称
            Console.WriteLine("获取文件名称包括路径: " + fileinfo.FullName);        // 获取文件名称包括路径
            Console.WriteLine("获取文件大小, 输出为MB: " + M / 1000000f + "M");           // 获取文件大小, 输出为 MB 


        }

        // 读写文件
        static void readwritefiles()
        {

            // 向文件内添加文字
            FileInfo fileinfo = new FileInfo("d:/Read.txt");    // 读入一个可写文件
            StreamWriter writer = fileinfo.AppendText();        // AppendText 返回一个StreamWrite 类型, 因此需要一个对象来接受传参.
            string time = DateTime.Now.ToString("hh:mm:ss");  // 创建一个时间值
            string text = "写入时间  " + time;                // 写入文件内容格式
            writer.WriteLine(text);     // 写入文件内容
            writer.Flush();             // 清理缓存并将缓存内数据写入文件.
            writer.Close();             // 关闭StreamWrite文件对象

            // 读取文件
            StreamReader sr = new StreamReader(fileinfo.OpenRead());  // OpenRead 返回一个FileStream 类型, 因此需要一个对象来接受传参.
            while (sr.Peek() != -1) { Console.WriteLine(sr.ReadLine()); }  // 读取文件所有文字

        }

        // 读写文件 2
        static void write_read_files()
        {
            FileInfo fileinfo = new FileInfo("d:/Read.txt");
            using (FileStream writer1 = fileinfo.OpenWrite())
            {
                Byte[] info = new UTF8Encoding(true).GetBytes("Hello World");
                writer1.Write(info, 0, info.Length);    // 将字节块写入文件流。
                                                        //      Write 参数:
                                                        //   array:
                                                        //     包含要写入该流的数据的缓冲区。
                                                        //   offset:
                                                        //     array 中的从零开始的字节偏移量,从此处开始将字节复制到该流。
                                                        //   count:
                                                        //     最多写入的字节数。



            }

            // Open the stream and read it back.
            using (FileStream fs = fileinfo.OpenRead())
            {
                byte[] b = new byte[1024];
                UTF8Encoding temp = new UTF8Encoding(true);

                while (fs.Read(b, 0, b.Length) > 0)  // 从流中读取字节块并将该数据写入给定缓冲区中。
                                                     //     参数:
                                                     //   array:
                                                     //     当此方法返回时,包含指定的字节数组,此数组中 offset 和 (offset + count - 1) 之间的值被从当前源中读取的字节所替换。
                                                     //   offset:
                                                     //     array 中的字节偏移量,将在此处放置读取的字节。
                                                     //   count:
                                                     //     最多读取的字节数。
                                                     // 返回结果:
                                                     //     读入缓冲区中的总字节数。 如果字节数当前不可用,则总字节数可能小于所请求的字节数;如果已到达流结尾,则为零。
                {
                    Console.WriteLine(temp.GetString(b));
                }
            }
        }


        // 创建空文件并读取文件
        static void textfile()
        {
            string path = @"d:\1.txt";

            FileInfo fi = new FileInfo(path);  // 文件路径

            // Check for existing file
            if (!fi.Exists)  // 判断文件是否为空
            {
                // Create the file.
                using (FileStream fs = fi.Create())  // Create 表示创建文件
                {
                    Byte[] info =
                        new UTF8Encoding(true).GetBytes("This is some text in the file.");  // 设置UTF8编码格式并将字符串的值转为byte数据

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

            // Open the stream and read it back.
            using (StreamReader sr = fi.OpenText()) // 读入文件内容
            {
                string? s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }
        }


        // 创建新文件
        static void newfile()
        {
            FileInfo fi = new FileInfo("d:/1.txt");  // 创建的文件名(包含路径)
            FileStream fs = fi.Create();             // 创建文件, 默认覆盖文件.
            // 默认情况下,向所有用户授予对新文件的完全读 / 写访问权限。此方法是 提供的 File.Create功能的包装器。

            fs.Close();       // 释放关联资源.   
            fi.Delete();      // 删除文件

        }


        // 创建新文件并写入文件
        static void writeNew()
        {
            FileInfo fi = new FileInfo("d:/2.txt");

            if (!fi.Exists)  // 如果文件没有值则为true
            {
                //Create a file to write to.
                using (StreamWriter sw = fi.CreateText())  // 写入文件
                {
                    sw.WriteLine("Hello");
                    sw.WriteLine("And");
                    sw.WriteLine("Welcome");
                }
            }

            //Open the file to read from.
            using (StreamReader sr = fi.OpenText()) // 读取文件
            {
                string? s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }
        }


        // 复制文文件, 将现有文件复制到新文件.
        // 有一个问题需要注意的是, 如果遇到需要管理员运行则需要在 应用程序清单文件(app.manifest) 修改UAC权限. 可以在主程序添加应用程序清单文件.
        static void Copys()
        {
            try
            {
                FileInfo fi = new FileInfo("d:/Typora_theme.rar");  // 源文件
                FileInfo newfi = fi.CopyTo("d:/Typora_theme1.rar", true); // 被复制的文件, 允许覆盖文件
                                                                          // CopyTo("参数1","参数2")
                                                                          // 参数1: 文件名
                                                                          // 参数2: bool 类型, 表示是否可以覆盖文件
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);  // 如果有错误则错误信息
            }
        }

        // 移动文件
        static void Moves()
        {
            FileInfo fileInfo = new FileInfo("D:/1.txt");
            fileInfo.MoveTo("c:/1.txt", true);  // 和CopyTo 参数是一样的
        }

        // 刷新文件
        // C# 中的 System.IO.FileInfo.Refresh() 方法用于刷新现有 FileSystemInfo 对象的状态,其中包括其属性和上次写入时间。
        // 此方法允许您更新有关文件或目录的信息(如果自创建对象以来已在外部更改)。
        // 通过调用 Refresh(),可以确保 FileInfo 对象反映有关文件或目录的最新信息。
        static void Refresh()
        {
            FileInfo fileInfo = new FileInfo("D:/1.txt");
            while (true) 
            {
                var R = fileInfo.LastAccessTime;  // 最后一次访问文件时间
                Thread.Sleep(1000);     // 阻塞1000毫秒
                Console.WriteLine(R);   // 输出
                fileInfo.Refresh();     // 刷新, 如果屏蔽则无法自动刷新
            }
            

        }

        // 创建符号链接
        static void newSymbol() 
        {
            FileInfo fileinfo = new FileInfo("d:/123.txt");
            // CreateSymbolicLink 创建快捷方式(符号链接), 参数path<string> 快捷方式路径, pathToTarget<string> 符号链接的目标目录。 如果当前存在文件则报错.
            File.CreateSymbolicLink("d:/123.txt", "e:/321.txt");        // 创建快捷方式(符号链接
            Console.WriteLine(fileinfo.LinkTarget);                     // 输出符号链接(快捷方式)的来源, 仅能支持 File.CreateSymbolicLink 创建的符号链接
        }


        // 修改文件内容并保存为新文件
        /// <summary>
        /// 指定文本批量更换.无返回值; 修改完会默认在当前文件夹中生成一个同文件名.rew的文件
        /// </summary>
        /// <param name="filename">需要更改文件名,包含路径.</param>
        /// <param name="old">旧字符</param>
        /// <param name="newz">新字符</param>
        static void ReplaceFile(string filename, string old, string newz)
        {
            // 读入文件
            string strings = "";

            FileInfo fileInfo = new FileInfo(filename);
            try
            {
                StreamReader sr = new StreamReader(fileInfo.OpenRead());  // OpenRead 返回一个FileStream 类型, 因此需要一个对象来接受传参.
                while (sr.Peek() != -1)
                {
                    strings = sr.ReadToEnd();
                    strings = strings.Replace(old, newz);
                    Console.WriteLine(strings);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            // 新建文件
            FileInfo file = new FileInfo(fileInfo.FullName + ".rew");
            if (!file.Exists)  // 如果文件没有值则为true
            {
                using (StreamWriter sw = file.CreateText())  // 写入新文件
                {
                    sw.WriteLine(strings); 
                    sw.Flush();
                    sw.Close();
                }
            }   
        }



        // 文件打开方式
        void Opens() 
        {
            string? strings, oldstr= "", newstr="";    // 新建string变量
            FileInfo fileInfo = new FileInfo("D:/1.txt");   // 指定文件
            using (FileStream fs = fileInfo.Open(FileMode.Open, FileAccess.Read))  // 打开文件方式.Open方法参数是枚举类型
            {
                byte[] b = new byte[1024];
                UTF8Encoding temp = new UTF8Encoding(true); 
                while (fs.Read(b, 0, b.Length) > 0) // 从流中读取字节块并将该数据写入给定缓冲区中。
                                                    //     参数:
                                                    //   array:
                                                    //     当此方法返回时,包含指定的字节数组,此数组中 offset 和 (offset + count - 1) 之间的值被从当前源中读取的字节所替换。
                                                    //   offset:
                                                    //     array 中的字节偏移量,将在此处放置读取的字节。
                                                    //   count:
                                                    //     最多读取的字节数。
                                                    // 返回结果:
                                                    //     读入缓冲区中的总字节数。 如果字节数当前不可用,则总字节数可能小于所请求的字节数;如果已到达流结尾,则为零。
                
                {
                    strings = temp.GetString(b);
                    strings = strings.Replace(oldstr, newstr);
                    Console.WriteLine(strings);
                }
            }
        }
    }  
}

 

posted @ 2024-03-24 08:25  edolf  阅读(23)  评论(0编辑  收藏  举报