C# System.IO和对文件的读写操作

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
             * ================ Path ===============
            string file = @"D:\a\b\c\one.txt";
            Console.WriteLine(Path.GetDirectoryName(file));  // 获取文件的路径
            Console.WriteLine(Path.GetExtension(file));  // 获取文件扩展名
            Console.WriteLine(Path.GetFileName(file));  // 获取文件名(包含扩展)
            Console.WriteLine(Path.GetFullPath("123.txt"));  // 可以根据相对路径获取全路径
            Console.WriteLine(Path.GetRandomFileName());  // 随即返回一个文件名(不重复的文件名)
            Console.WriteLine(Path.GetTempPath());  // 返回一个临时目录
            Console.ReadKey();
            */
            /*
             * ========================= File ===============================
            string logName = "delete.txt";  // 文件名
            string filePath = Path.GetFullPath(logName);  // 获取全路径
            if (!File.Exists(filePath))
            {
                // 如果文件不存在
                File.Create(filePath).Close();  // 创建文件并且关闭
            }
            // 读取还可以使用 File.ReadAllLines(filePath)按行读取
            string logtext = File.ReadAllText(filePath);  // 读取文件
            Console.WriteLine(logtext);
            logtext += "\r\n" + DateTime.Now.Date;
            Console.WriteLine(filePath);
            File.WriteAllText(filePath, logtext);  // 将内容写进文本
            Console.ReadKey();
            */
            /*
             * ======================= FileInfo ==============================
            string fileName = "delete.txt";
            string filePath = Path.GetFullPath(fileName);
            FileInfo fi = new FileInfo(fileName);  // 创建管理文件的软连接
            if (!fi.Exists)
            {
                Console.WriteLine("文件不存在!!!");
            }
            var writeThing = fi.AppendText();  // 追加方式
            writeThing.WriteLine(DateTime.Now.ToString());  // 追加文本
            writeThing.Close();  // 关闭
            var readThing = fi.OpenText();  // 读取
            Console.WriteLine(readThing.ReadToEnd());
            readThing.Close();  // 关闭
            Console.ReadKey();
            */
            /*
             * ================================== Directory ===========================================
            string filePath = @"F:\下载\C#完整版.NET教程(价值398元)\04NetFramework\【IT教程网】04NetFramework\Day02";
            string fileP = filePath + @"\abc";
            if (!Directory.Exists(fileP))
            {
                // 判断文件是否存在,如果文件不存在那么创建文件目录
                Directory.CreateDirectory(fileP);
            }
            foreach(var item in Directory.GetFiles(filePath)){
                Console.WriteLine(item);  // 输出该文件下的子文件名称
            }
            Console.WriteLine("\r\n");
            foreach(var item in Directory.GetDirectories(filePath))
            {
                Console.WriteLine(item);  // 输出该目录下的子目录
            }
            Console.WriteLine(Directory.GetParent(filePath));  // 返回父类目录
            Console.ReadKey();
            */
            /*
             * ======================== DirectoryInfo ================================
            string filePath = @"F:\下载\C#完整版.NET教程(价值398元)\04NetFramework\【IT教程网】04NetFramework\Day02";
            DirectoryInfo dir = new DirectoryInfo(filePath);
            dir.CreateSubdirectory(@"ab\cd\ef\gh\kj");  // 可连续创建
            foreach (var item in dir.GetDirectories())
            {
                Console.WriteLine(item);  // 输出当前文件夹子目录
            }
            Console.WriteLine("\n");
            foreach(var item in dir.GetDirectories())
            {
                Console.WriteLine(item);  // 输出当前文件夹子目录
            }
            Console.ReadKey();
            */
            /*
             * ================================== DriveInfo =================================
            // 对磁盘进行操作
            foreach(DriveInfo item in DriveInfo.GetDrives())
            {
                Console.WriteLine(item);  // 获取所有驱动的名称(显示磁盘的数量)
                Console.WriteLine(item.DriveType);  // 获取类型
                if (item.IsReady)
                {
                    // 判断磁盘是否准备就绪
                    Console.WriteLine(item.DriveFormat);  // 获取存储格式
                    Console.WriteLine(item.TotalSize);  // 获取磁盘大小,默认是比特单位
                    Console.WriteLine((item.TotalSize * 1.0) / (1024.0*1024.0*1024.0));  // 单位转换,KB/M/G
                    Console.WriteLine((item.TotalFreeSpace * 1.0) / (1024.0 * 1024.0 * 1024.0));  // 剩余可用路径,这里转换为G
                }
                Console.WriteLine();
            }
            Console.ReadKey();
            */
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            // 文件系统的监控 FileSystemWatcher
            FileSystemWatcher watcher = new FileSystemWatcher(@"F:\下载\C#完整版.NET教程(价值398元)\04NetFramework\【IT教程网】04NetFramework\Day02");  // 监听该目录
            watcher.NotifyFilter = (NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName);  // 设置过滤器,LastAccess上一次打开的日期,LastWrite最后一次修改,FileName/DirectoryName文件名或者目录名的修改
            // 事件的注册
            watcher.Changed += new FileSystemEventHandler(OnChanged);  // 监听改变事件,函数OnChanged里面的事件
            watcher.Created += new FileSystemEventHandler(OnChanged);  // 监听创建事件,函数OnChanged里面的事件
            watcher.Deleted += new FileSystemEventHandler(OnChanged);  // 监听删除事件,函数OnChanged里面的事件
            watcher.Renamed += new RenamedEventHandler(OnRenamed);  // 监听重命名事件,函数OnChanged里面的事件
            watcher.Error += new ErrorEventHandler(OnError);  // 监听错误事件,函数OnError里面的事件
            watcher.EnableRaisingEvents = true;  // 启用组件
            Console.WriteLine("Press 'Enter' to exit...");
            Console.ReadKey();
        }
        // OnChanged事件
        private static void OnChanged(object source, FileSystemEventArgs e)
        {
            WatcherChangeTypes changeType = e.ChangeType;  // 获取发生的类型
            // e.FullPath获取文件路径及其文件名
            Console.WriteLine("The File {0}=>{1}", e.FullPath, changeType.ToString());
        }
        // OnRenamed事件
        private static void OnRenamed(object source, RenamedEventArgs e)
        {
            WatcherChangeTypes changeType = e.ChangeType;
            // e.OldFullPath 获取改变前文件路径及其文件名
            Console.WriteLine("The File {0} {2} to {1}", e.OldFullPath, e.FullPath, changeType.ToString());
        }
        private static void OnError(object source, ErrorEventArgs e)
        {
            Console.WriteLine("An error has occurred.");
        }
    }
}

对文件的读写操作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            // 不常用(实际不会这样子用)
            /*
            // 使用FileStream类来管理文件数据
            string overview = "Most commercial application, such as...";  // 定义写入的字符串
            FileInfo fileStore = new FileInfo("123.txt");  // 打开对应的文件,默认当前路径
            FileStream conduit = fileStore.Create();  // 创建
            byte[] encodedOverview = new UTF8Encoding(true).GetBytes(overview);  // encodedOverview数组格式的,将其进行编码
            conduit.Write(encodedOverview, 0, encodedOverview.Length);  // 将编码后的内容(第一个参数固定式byte数组)写进去,需要传递从那个位置开始,多长
            conduit.Close();  // 关闭
            */
            //
            /*
            // 使用MemoryStream类来管理内存数据
            byte[] overview = new UTF8Encoding(true).GetBytes("Most commercial application, such as...");  // 同样编码字符串
            MemoryStream conduit = new MemoryStream(overview.Length);  // 开辟内存空间
            conduit.Write(overview, 0, overview.Length);  // 进行写入,起始位置,长度
            Console.WriteLine(conduit.Position.ToString());  // 获取写入指针的当前位置
            conduit.Flush();  // 缓存的数据写进内存空间
            conduit.Seek(0, SeekOrigin.Begin);  // 将文件指正写入到首部
            // 读取
            byte[] overviewRead = new byte[conduit.Length];  // 创建内存流
            conduit.Read(overviewRead, 0, ((int)conduit.Length));  // 读取,从0开始读取,读取长度为((int)conduit.Length)
            Console.WriteLine(new UTF8Encoding().GetChars(overviewRead));
            conduit.Close();
            */
            //
            /*
            // 使用BufferedStream来提高流性能
            string overview = "Most commercial application, such as...";  // 字符串
            FileInfo fileStore = new FileInfo("123.txt");  // 打开文件
            FileStream conduit = fileStore.Create();  // 创建
            BufferedStream fileBuffer = new BufferedStream(conduit);  // 创建缓冲区
            byte[] encodedOverview = new UTF8Encoding(true).GetBytes(overview);  // 编码内容
            fileBuffer.Write(encodedOverview, 0, encodedOverview.Length);  // 写进缓冲区
            fileBuffer.Close();  // 关闭缓冲区
            conduit.Close();  // 关闭文件流
            */
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // 常用(简便)
            //
            // 两大分类: 二进制文件、文本文件
            // 二进制文件区分BinaryReader/BinaryWriter
            // 文本文件又分为:文件、字符串。区分:StringReader/StringWriter
            //
            // 下面的文本文件读取
            /*
            // 不使用数据库和文件的情况下存储字符串
            StringBuilder sb = new StringBuilder();
            TextWriter tw = new StringWriter(sb);
            // 写内容(支持多种重载)
            tw.Write("您好,");
            tw.Write(123);
            tw.Write("\tData:{0}\t", DateTime.Now);
            tw.WriteLine("bye!");
            // 读取操作
            TextReader tr = new StringReader(sb.ToString());  // 注意传递进去的是字符串
            Console.WriteLine(tr.ReadToEnd());  // 读取
            Console.ReadKey();
            */
            //
            /*
            // 对文件进行操作
            TextWriter tw = new StreamWriter("123.txt");  // 读取当前路径下的文件
            // 写入同上
            tw.Write("您好,");
            tw.Write(123);
            tw.Write("\tData:{0}\t", DateTime.Now);
            tw.WriteLine("bye!");
            tw.Close();  // 关闭
            // 读取
            TextReader tr = new StreamReader("123.txt");
            Console.WriteLine(tr.ReadToEnd());
            // 下面是二进制的
            Stream sm = new FileStream("456.dat", FileMode.OpenOrCreate);  // 如果文件存在就打开文件,如果文件不存在那么创建并打开文件
            BinaryWriter bw = new BinaryWriter(sm);
            bw.Write(true);
            bw.Write(123);
            bw.Write("hello");
            bw.Close();
            sm.Close();
            // 读取
            BinaryReader sr = new BinaryReader(new FileStream("456.dat", FileMode.Open));
            bool b = sr.ReadBoolean();  // 读取bool
            int i = sr.ReadInt32();  // 读取整型
            string s = sr.ReadString();  // 读取字符串
            Console.WriteLine("bool值:{0},整型:{1},字符型:{2}", b, i, s);
            Console.ReadKey();
            sr.Close();
            // 注:值得注意的是二进制的读写一定要保持他们的顺序,不然会报错
            */
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/namejr/p/10424242.html