c#文件操作

                                                                                                                                                                           

一、 File文件创建、复制、移动、删除操作

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace 文件创建复制移动删除操作
{
    class Program
    {
        static void Main(string[] args)
        {
            //设置控制台标题和指明文件路径
            Console.Title="文件创建、复制、移动、删除操作";
            string path1 = "1.txt";
            string path2 = "2.txt";
            string path3="d:\3.txt";
            string path4 = @"c:4.txt";

            //要写入的文本字符串
            string msg = "文件基本操作示例";
            msg += Environment.NewLine + "   A.创建文件;B.复制文件;C.移动文件;D:删除文件;";//Environment.NewLine属性用于获取为当前环境定义的换行字符串

            //在path1指定的路径中创建或覆盖文件,并将msg字符串写入文件中。
            FileStream fs = File.Create(path1);//创建文件流,在path1指定的路径中创建或覆盖文件
            byte[] contents = Encoding.Default.GetBytes(msg);//将msg字符串的字符编码变成当前ANSI代码页的编码并保存到byte数组中
            fs.Write(contents,0,contents.Length);//从contents中读取字符串,从0位置开始将字符串长度大小的字符串写入到文本中。
            fs.Close();//关闭文件流

            //打印写入paht1路径下文件内容
            string str=File.ReadAllText(path1,Encoding.Default);//读取path1指定的文件中的所有文本内容保存到字符串str中中。
            Console.WriteLine("1.txt已经被成功创建!

");
            Console.WriteLine("	创建1.txt并写入文件,其内容如下:

");
            Console.WriteLine(" "+str );
            Console.ReadKey();

            //将path1路径下文件复制到path2指定的路径
            if(File.Exists(path2))//如果path2下有同名文件就将其删除
                File.Delete(path2);
            File.Copy(path1,path2);//将path1路径下的文件复制到文件path2路径下的文件
            Console.WriteLine("
1.txt被成功复制出一个2.txt");
            Console.ReadKey();

            //将path1路径下文件移动到path3指定的路径
            File.Move(path1, path3);
            Console.WriteLine("
1.txt文件被成功移到D盘根目录并重命名为3.txt");
            Console.ReadKey();

            //将path2路径下文件移动到path4指定的路径
            File.Move(path2, path4);
            Console.WriteLine("
2.txt一个文件被成功移动到C盘并更名为4.txt");
            Console.ReadKey();

            //删除三个文件
            File.Delete(path2);
            File.Delete(path3);
            File.Delete(path4);
            Console.WriteLine("
三个文件被成功删除。");
            Console.ReadKey();
        }
    }
}

程序截图:

                                                               

、文件类File读取记事本内容

主要知识点:

一. FileStream file_read = new FileStream("1.txt", FileMode.Open, FileAccess.Read);//只读权限打开1.txt文件

参数1:

"1.txt":文件路径,通常用字符串变量或者字符串常量表示,如:"d:\1.txt";

参数2:

FileMode.Open:打开模式,此种方式如果存在则打开,否则抛出异常。

FileMode.Append:追加模式,打开文件或新建文件并查找到文件尾,只能在FileAccess.Write权限下使用。

FileMode.Create:指定操作系统创建文件,如果已存在相同名称文件,则覆盖。

FileMode.CreateNew:指定操作系统创建文件,如果已存在相同名称文件,则抛出异常。

FileMode.OpenOrCreate:如果文件存在,则打开。如果不存在则新建一个文件。

FileMode.Truncate:打开现有文件,文件一旦被打开就被截断为0字节大小。

参数3:

FileAccess.Read:只读写权限

FileAccess.ReadWrite:读写权限

FileAccess.Write:写权限

 二、StreamReader sr = new StreamReader(file_read,Encoding.Default);//获取读入流读取1.txt

参数1:

file_read:获取文件流,即获取指定文件文件流,通常用字符串变量表示。

参数2:

Encoding.Default:获取操作系统的当前ANSI代码页的编码

Encoding.UTF8:获取UTF8格式的编码

Encoding.Unicode:获取Unocode格式的编码

Encoding.ASCII:获取ASCLL格式的编码

Encoding.Convert (Encoding, Encoding, Byte[]) :将一种编码方式转换成另一种编码方式。

Encoding.Convert (Encoding, Encoding, Byte[], Int32, Int32) :將某一范围内由一种编码方式转换成另一种编码方式。

 三、string[] filelist = File.ReadAllLines("1.txt", Encoding.Default);//读取文件内容所有行保存到字符串数组中。

四、string line = sr.ReadLine();//读取一行文件内容,从读入流获取内容。

 例子一:

核心方法:string[] filelist = File.ReadAllLines("1.txt", Encoding.Default);//读取文件内容所有行保存到字符串数组中

代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace studyread
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream file_read = new FileStream("1.txt", FileMode.Open, FileAccess.Read);//新建文件流,只读权限打开1.txt文件

            string[] filelist = File.ReadAllLines("1.txt", Encoding.Default);//读取文件内容所有行保存到字符串数组中。

            //循环打印读入内容。
            for (int i = 0; i <= filelist.Length - 1; i++)
            {
                Console.WriteLine("第{0}行内容为:{1}", i, filelist[i]);
            }
            Console.ReadKey();
        }        
    }
}

运行截图:

 例子二:

 核心语句:string line = sr.ReadLine();//读取一行文件内容,从读入流获取内容。

代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace studyread
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream file_read = new FileStream("1.txt", FileMode.Open, FileAccess.Read);//新建文件流,只读权限打开1.txt文件
            StreamReader sr = new StreamReader(file_read, Encoding.Default);//新建读入流取文件流 
           
            string line= sr.ReadLine();;//读取一行内存保存给字符串line
            Console.WriteLine(line);

            Console.ReadKey();
        }
    }
}

 运行截图:

 当然上列代码利用循环也可以将所有内容读取出来,达到例子一的效果。

修改源码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace studyread
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream file_read = new FileStream("1.txt", FileMode.Open, FileAccess.Read);//新建文件流,只读权限打开1.txt文件
            StreamReader sr = new StreamReader(file_read, Encoding.Default);//新建读入流取文件流 

            string[] filelist = File.ReadAllLines("1.txt", Encoding.ASCII);//这里主要用来获取总行数filelist.Length
            string line;//定义字符串变量line,用来保存读取的内容

            //循环读取并打印文件每一行内容,即
            for (int i = 0; i <= filelist.Length - 1; i++)
            {
                line = sr.ReadLine();//读取一行内容保存到字符串line中。
                Console.WriteLine(line);
            }

            Console.ReadKey();
        }
    }
}

 程序截图:

附录记事本文件内容:

                                                                                                                                                                            

                                                                 

三、文件类File写入和追加记事本内容

代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace study文件操作
{
    class Program
    {
        static void Main(string[] args)
        {
            //控制台标题设置和指定文件路径
            Console.Title = "文件读写操作实例";//控制台标题
            string path = "d:\test.txt"; //指定文件绝对路径

            //定义要写入和追加的字符串
            string[] strs = { "窗前明月光,", "疑是地上霜." };//要写入的字符串
            string contents = "明月几时有?" + Environment.NewLine + "把酒问青天";//要追加的字符串

            //获取文件绝对路径
            Console.WriteLine("文件绝对路径如下:
{0}", Path.GetFullPath(path));//获取文件绝对路径
            Console.ReadKey();

            //将字符串写入文件
            /*Encoding.Default属性用于获取操作系统当前ANSI代码页的编码*/
            File.WriteAllLines(path, strs, Encoding.Default);//文件存在则打开,否则建立文件并写入内容
            Console.WriteLine("
要写入的字符串已经成功写入文件!");
            Console.ReadKey();

            //字符串追加文件
            File.AppendAllText(path, contents, Encoding.Default);//将字符串追加到文本末尾
            Console.WriteLine("文件追加字符串成功!
");
            Console.ReadKey();

            //获取文件行数,并打印总行数
            string[] lines = File.ReadAllLines(path, Encoding.Default);//获取文件总行数
            Console.WriteLine("文件包含以下{0}行内容", lines.Length);
            Console.ReadKey();
            
            //逐行打印每行内容
            for (int i = 0; i < lines.Length; i++) 
            {
                Console.WriteLine("  "+lines[i]);
            }

            //获取并打印文件建立、修改、访问时间
            Console.WriteLine("
文件创建时间:{0:F}",File.GetCreationTime(path));
            Console.WriteLine("文件最后修改时间:{0:F}",File.GetLastWriteTime(path));
            Console.WriteLine("文件最后访问时间:{0:F}",File.GetLastAccessTime(path));
            Console.ReadKey();
        }
    }
}

程序运行截图:

                                                                                                     

四、c#用FileInfo类复制、移动、删除文件

源码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace 文件信息类FileInfo
{
    class Program
    {
        static void Main(string[] args)
        {
            //设置控制台标题和指明文件路径
            Console.Title = "用FileInfo类执行文件操作示例";
            string path1 = "1.txt";
            FileInfo myFile = new FileInfo(path1);

            //创建并写入文本
            //创建写入新文本文件的StreamWriter
            using (StreamWriter sw = myFile.CreateText()) 
            {
                //WriteLine方法后跟行结束符的字符串写入文本流
                sw.WriteLine("白日依山尽,黄河入海流。");
                sw.WriteLine("欲穷千里目,更上一层楼。");
                Console.WriteLine("文本文件创建成功!");
            }

            //追加文本
            //创建一个StreamWriter,在FileInfo指定的文本选中追加文本
            using (StreamWriter sw = myFile.AppendText())
            {
                //WriteLine方法后跟行结束符的字符串写入文本流
                sw.WriteLine("问君能有几多愁?恰似一江春水向东流");
                sw.WriteLine("明月几时有?把酒问青天");
                Console.WriteLine("文本文件追加成功!");
            }
            
            //读取文本
            //创建从现有文本文件中进行读取的StreamReader
            using (StreamReader sr = myFile.OpenText()) //创建使用UTF8编码并从现有文件读取的StreamReader
            {
                string s = "";
                
                //Readline方法从当前流中读取一行字符并将数据作为字符串返回

                Console.WriteLine("
文本文件内容如下:");
                while ((s = sr.ReadLine()) != null) 
                {
                    Console.WriteLine("    " + s);
                }
            }

            //列出文本文件的相关信息
            Console.WriteLine("
文件所在目录:{0}", myFile.DirectoryName);
            Console.WriteLine("
文件扩展名:{0}", myFile.Extension);
            Console.WriteLine("
文件大小:{0}字节", myFile.Length);
            Console.WriteLine("
文件创建时间:", myFile.CreationTime);
            Console.WriteLine("
文件最后修改时间:{0:F}", myFile.LastWriteTime);
            Console.WriteLine("
文件最后访问时间:{0:F}", myFile.LastAccessTime);

            //复制文件和删除文件
            try
            {
                string path2 = path1 + ".tmp";
                FileInfo file2 = new FileInfo(path2);
                myFile.CopyTo(path2);//复制文件
                Console.WriteLine("
文件{0}已经被复制到{1}", path1, path2);
                Console.ReadKey();
                file2.Delete();//删除文件
                Console.WriteLine("
文件{0}已被成功删除!
", path2);
            }
            catch (Exception e)
            {
                Console.WriteLine("
文件操作失败:{0}", e.ToString());
            }
            Console.ReadKey();
        }
    }
}

                                                                       

五、FileStream文件流写入和读取记事本文件

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace 文件流FileStream
{
    class Program
    {
        static void Main(string[] args)
        {
            //设置控制台标题,指明文件路径。
            Console.Title = "FileStream文件流操作示例";
            const string path = "Test.txt";//const 关键字用于修改字段或局部变量的声明。它指定字段或局部变量的值是常数,不能被修改

            //定义要写入的字符串
            string n1 = Environment.NewLine;
            string str = "题西林壁" + n1 + "横看成岭侧成峰,远近高低各不同。" + n1 + "不识庐山真面目,只缘身在此山中。";

            //将str中的字符串复制到字符数组charData中
            char[] charData = str.ToCharArray();
            int count = Encoding.Default.GetByteCount(charData);//count保存charData字符数组的中的所有字符编码产生的字节数
            byte[] byteData1 = new byte[count];//新建一个编码后字节大小的字符数组bytaData1
            byte[] byteData2 = new byte[count];//新建一个编码后的字节大小的字符数组bytaData2
            byte[] byteData3 = new byte[40];//新建一个编码后的字节大小为40的字符数组。
            try
            {
                FileStream fs = new FileStream(path, FileMode.Create);//如果Test.txt已经存在,则覆盖,否则创建Test.txt文件
                Encoder encoder = Encoding.Default.GetEncoder();//获取一个解码器
                encoder.GetBytes(charData, 0, charData.Length, byteData1, 0, true);//将charData字符数组全部内容,进行解码。
                fs.Seek(0, SeekOrigin.Begin);//光标定位到文件开始
                fs.Write(byteData1, 0, byteData1.Length);//从byteData中的0字节处开始写入数据,写完为止
                Console.WriteLine("文件创建成功!");
                fs.Close();
            }
            catch (IOException e) 
            {
                Console.WriteLine("文件写入操作失败:{0}
", e.ToString());
                return;
            }
            try
            {
                FileStream fs = new FileStream(path, FileMode.Open);//以打开模式新建文件流
                fs.Seek(0, SeekOrigin.Begin);//光标定位文件开始处
                fs.Read(byteData2, 0, count);//从缓冲区0字节处读取数据,从byteData2中的0字节处开始保存,保存所有内容。
                fs.Seek(44, SeekOrigin.Begin);//光标定位到44字节处
                fs.Read(byteData3, 0, 40);//从缓冲区44字节处读取数据,从byteData3中的0字节处开始保存,保存剩下内容。
                fs.Close();
            }
            catch (IOException e) 
            {
                Console.WriteLine("文件读取失败:{0}", e.ToString());
            }
            string content1 = Encoding.Default.GetString(byteData2);//将byteData2字符数组解码成字符串
            Console.WriteLine("
文本内容如下:");
            Console.WriteLine(content1);
            string content2 = Encoding.Default.GetString(byteData3);//将byteData3字符数组解码成字符串
            Console.WriteLine("
从文件中读取40个字节:");
            Console.WriteLine(content2);
            Console.WriteLine();
            Console.ReadKey();
        }
    }
}

程序运行截图:

                                                                         

六、用StreamWriter类写入文件应用示例

代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace 流写入类StreamWriter
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "用StreamWriter类写入文件应用示例";
            string path = "Test.txt";
            StreamWriter sw = new StreamWriter(path, false, Encoding.Default, 512);
            sw.WriteLine("春晓");
            sw.WriteLine("春明不觉晓,处处闻啼鸟。");
            sw.WriteLine("夜来风雨声,花落知多少.");
            sw.Close();
            Console.WriteLine("文本文件写入成功!
");
            Console.ReadKey();
        }
    }
}

程序截图:

七、StreamReader类读取文件应用示例

源码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace StreamReader学习
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "用StrreamReader类读取文件应用示例";
            string path = "Test.txt";
            try
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                using (StreamWriter sw = new StreamWriter(path))
                {
                    sw.WriteLine("          早发白帝城");
                    sw.WriteLine("朝辞白帝彩云间,千里江陵一日还。");
                    sw.WriteLine("两岸猿声啼不住,轻舟已过万重山。");
                    Console.WriteLine("文本文件创建成功!");
                } 

                Console.WriteLine("文件内容如下:");
                using (StreamReader sr = new StreamReader(path))
                {
                    while (sr.Peek() >= 0)
                    {
                        Console.WriteLine("   " + sr.ReadLine());
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("文件操作过程失败:{0}
", e.ToString());
            }
            Console.ReadKey();
        }
    }
}

程序截图:

原文地址:https://www.cnblogs.com/xingyunblog/p/3913371.html