• C# File类常用方法


    File 类

      提供用于创建、复制、删除、移动和打开文件的静态方法,并协助创建 FileStream 对象。  

     1. File.Exists ——  确定指定的文件是否存在。

       public static bool Exists(string path)

    string curFile = @"c:	emp	est.txt";
    Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");

     2. File.AppendAllText 方法 —— 将指定的字符串追加到文件中,如果文件还不存在则创建该文件。

       public static void AppendAllText(string path,string contents)
    using System;
    using System.IO;
    using System.Text;
    
    class Test
    {
        public static void Main()
        {
            string path = @"c:	empMyTest.txt";
    
            // This text is added only once to the file.
            if (!File.Exists(path))
            {
                // Create a file to write to.
                string createText = "Hello and Welcome" + Environment.NewLine;
                File.WriteAllText(path, createText);
            }
    
            // This text is always added, making the file longer over time
            // if it is not deleted.
            string appendText = "This is extra text" + Environment.NewLine;
            File.AppendAllText(path, appendText);
    
            // Open the file to read from.
            string readText = File.ReadAllText(path);
            Console.WriteLine(readText);
        }
    }
    View Code

      void public static void AppendAllText(string path,string contents,Encoding encoding)

    using System;
    using System.IO;
    using System.Text;
    
    class Test
    {
        public static void Main()
        {
            string path = @"c:	empMyTest.txt";
    
            // This text is added only once to the file.
            if (!File.Exists(path))
            {
                // Create a file to write to.
                string createText = "Hello and Welcome" + Environment.NewLine;
                File.WriteAllText(path, createText, Encoding.UTF8);
            }
    
            // This text is always added, making the file longer over time
            // if it is not deleted.
            string appendText = "This is extra text" + Environment.NewLine;
            File.AppendAllText(path, appendText, Encoding.UTF8);
    
            // Open the file to read from.
            string readText = File.ReadAllText(path);
            Console.WriteLine(readText);
        }
    }
    View Code

     3. File.ReadAllText 方法 —— 打开一个文本文件,将文件的所有行读入一个字符串,然后关闭该文件。

      public static string ReadAllText(string path)

    using System;
    using System.IO;
    using System.Text;
    
    class Test
    {
        public static void Main()
        {
            string path = @"c:	empMyTest.txt";
    
            // This text is added only once to the file.
            if (!File.Exists(path))
            {
                // Create a file to write to.
                string createText = "Hello and Welcome" + Environment.NewLine;
                File.WriteAllText(path, createText);
            }
    
            // This text is always added, making the file longer over time
            // if it is not deleted.
            string appendText = "This is extra text" + Environment.NewLine;
            File.AppendAllText(path, appendText);
    
            // Open the file to read from.
            string readText = File.ReadAllText(path);
            Console.WriteLine(readText);
        }
    }
    View Code

      public static string ReadAllText(string path,Encoding encoding)

      

    using System;
    using System.IO;
    using System.Text;
    
    class Test
    {
        public static void Main()
        {
            string path = @"c:	empMyTest.txt";
    
            // This text is added only once to the file.
            if (!File.Exists(path))
            {
                // Create a file to write to.
                string createText = "Hello and Welcome" + Environment.NewLine;
                File.WriteAllText(path, createText, Encoding.UTF8);
            }
    
            // This text is always added, making the file longer over time
            // if it is not deleted.
            string appendText = "This is extra text" + Environment.NewLine;
            File.AppendAllText(path, appendText, Encoding.UTF8);
    
            // Open the file to read from.
            string readText = File.ReadAllText(path);
            Console.WriteLine(readText);
        }
    }
    View Code

     4. File.ReadAllLines 方法 —— 打开一个文本文件,将文件的所有行都读入一个字符串数组,然后关闭该文件。

      public static string[] ReadAllLines(string path)

    using System;
    using System.IO;
    class Test
    {
        public static void Main()
        {
            string path = @"c:	empMyTest.txt";
    
            // This text is added only once to the file.
            if (!File.Exists(path))
            {
                // Create a file to write to.
                string[] createText = { "Hello", "And", "Welcome" };
                File.WriteAllLines(path, createText);
            }
    
            // This text is always added, making the file longer over time
            // if it is not deleted.
            string appendText = "This is extra text" + Environment.NewLine;
            File.AppendAllText(path, appendText);
    
            // Open the file to read from.
            string[] readText = File.ReadAllLines(path);
            foreach (string s in readText)
            {
                Console.WriteLine(s);
            }
        }
    }
    View Code

      public static string[] ReadAllLines(string path,Encoding encoding)

    using System;
    using System.IO;
    using System.Text;
    
    class Test
    {
        public static void Main()
        {
            string path = @"c:	empMyTest.txt";
    
            // This text is added only once to the file.
            if (!File.Exists(path))
            {
                // Create a file to write to.
                string[] createText = { "Hello", "And", "Welcome" };
                File.WriteAllLines(path, createText, Encoding.UTF8);
            }
    
            // This text is always added, making the file longer over time
            // if it is not deleted.
            string appendText = "This is extra text" + Environment.NewLine;
            File.AppendAllText(path, appendText, Encoding.UTF8);
    
            // Open the file to read from.
            string[] readText = File.ReadAllLines(path, Encoding.UTF8);
            foreach (string s in readText)
            {
                Console.WriteLine(s);
            }
        }
    }
    View Code

     5. File.WriteAllText 方法 —— 创建一个新文件,在文件中写入内容,然后关闭文件。 如果目标文件已存在,则覆盖该文件。

      public static void WriteAllText(string path,string contents)  

    using System;
    using System.IO;
    using System.Text;
    
    class Test
    {
        public static void Main()
        {
            string path = @"c:	empMyTest.txt";
    
            // This text is added only once to the file.
            if (!File.Exists(path))
            {
                // Create a file to write to.
                string createText = "Hello and Welcome" + Environment.NewLine;
                File.WriteAllText(path, createText);
            }
    
            // This text is always added, making the file longer over time
            // if it is not deleted.
            string appendText = "This is extra text" + Environment.NewLine;
            File.AppendAllText(path, appendText);
    
            // Open the file to read from.
            string readText = File.ReadAllText(path);
            Console.WriteLine(readText);
        }
    }
    View Code

      public static void WriteAllText(string path,string contents,Encoding encoding)

    using System;
    using System.IO;
    using System.Text;
    
    class Test
    {
        public static void Main()
        {
            string path = @"c:	empMyTest.txt";
    
            // This text is added only once to the file.
            if (!File.Exists(path))
            {
                // Create a file to write to.
                string createText = "Hello and Welcome" + Environment.NewLine;
                File.WriteAllText(path, createText, Encoding.UTF8);
            }
    
            // This text is always added, making the file longer over time
            // if it is not deleted.
            string appendText = "This is extra text" + Environment.NewLine;
            File.AppendAllText(path, appendText, Encoding.UTF8);
    
            // Open the file to read from.
            string readText = File.ReadAllText(path);
            Console.WriteLine(readText);
        }
    }
    View Code

     6. File.WriteAllLines 方法 —— 创建一个新文件,在其中写入一个或多个字符串,然后关闭该文件。

      public static void WriteAllLines(string path,string[] contents)

    using System;
    using System.IO;
    class Test
    {
        public static void Main()
        {
            string path = @"c:	empMyTest.txt";
    
            // This text is added only once to the file.
            if (!File.Exists(path))
            {
                // Create a file to write to.
                string[] createText = { "Hello", "And", "Welcome" };
                File.WriteAllLines(path, createText);
            }
    
            // This text is always added, making the file longer over time
            // if it is not deleted.
            string appendText = "This is extra text" + Environment.NewLine;
            File.AppendAllText(path, appendText);
    
            // Open the file to read from.
            string[] readText = File.ReadAllLines(path);
            foreach (string s in readText)
            {
                Console.WriteLine(s);
            }
        }
    }
    View Code

      public static void WriteAllLines(string path,string[] contents,Encoding encoding)

    using System;
    using System.IO;
    using System.Text;
    
    class Test
    {
        public static void Main()
        {
            string path = @"c:	empMyTest.txt";
    
            // This text is added only once to the file.
            if (!File.Exists(path))
            {
                // Create a file to write to.
                string[] createText = { "Hello", "And", "Welcome" };
                File.WriteAllLines(path, createText, Encoding.UTF8);
            }
    
            // This text is always added, making the file longer over time
            // if it is not deleted.
            string appendText = "This is extra text" + Environment.NewLine;
            File.AppendAllText(path, appendText, Encoding.UTF8);
    
            // Open the file to read from.
            string[] readText = File.ReadAllLines(path, Encoding.UTF8);
            foreach (string s in readText)
            {
                Console.WriteLine(s);
            }
        }
    }
    View Code

      

     7.1. File.Create 方法 —— 在指定路径中创建或覆盖文件。

      public static FileStream Create(string path)

    using System;
    using System.IO;
    using System.Text;
    
    class Test
    {
        public static void Main()
        {
            string path = @"c:	empMyTest.txt";
    
            try
            {
    
                // Delete the file if it exists.
                if (File.Exists(path))
                {
                    // Note that no lock is put on the
                    // file and the possibility exists
                    // that another process could do
                    // something with it between
                    // the calls to Exists and Delete.
                    File.Delete(path);
                }
    
                // Create the file.
                using (FileStream fs = File.Create(path))
                {
                    Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
                    // Add some information to the file.
                    fs.Write(info, 0, info.Length);
                }
    
                // Open the stream and read it back.
                using (StreamReader sr = File.OpenText(path))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(s);
                    }
                }
            }
    
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.ToString());
            }
        }
    }
    View Code

     7.2 File.Copy 方法 —— 将现有文件复制到新文件。

      public static void Copy(string sourceFileName,string destFileName将现有文件复制到新文件。 不允许覆盖同名的文件。

    string sourceDir = @"c:current";
    string backupDir = @"c:archives2008";
    
    try
    {
        string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
        string[] txtList = Directory.GetFiles(sourceDir, "*.txt");
    
        // Copy picture files.
        foreach (string f in picList)
        {
            // Remove path from the file name.
            string fName = f.Substring(sourceDir.Length + 1);
    
            // Use the Path.Combine method to safely append the file name to the path.
            // Will overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
        }
    
        // Copy text files.
        foreach (string f in txtList)
        {
    
            // Remove path from the file name.
            string fName = f.Substring(sourceDir.Length + 1);
    
            try
            {
                // Will not overwrite if the destination file already exists.
                File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
            }
    
            // Catch exception if the file was already copied.
            catch (IOException copyError)
            {
                Console.WriteLine(copyError.Message);
            }
        }
    
        // Delete source files that were copied.
        foreach (string f in txtList)
        {
            File.Delete(f);
        }
        foreach (string f in picList)
        {
            File.Delete(f);
        }
    }
    
    catch (DirectoryNotFoundException dirNotFound)
    {
        Console.WriteLine(dirNotFound.Message);
    }
    View Code

      public static void Copy(string sourceFileName,string destFileName,bool overwrite)

    string sourceDir = @"c:current";
    string backupDir = @"c:archives2008";
    
    try
    {
        string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
        string[] txtList = Directory.GetFiles(sourceDir, "*.txt");
    
        // Copy picture files.
        foreach (string f in picList)
        {
            // Remove path from the file name.
            string fName = f.Substring(sourceDir.Length + 1);
    
            // Use the Path.Combine method to safely append the file name to the path.
            // Will overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
        }
    
        // Copy text files.
        foreach (string f in txtList)
        {
    
            // Remove path from the file name.
            string fName = f.Substring(sourceDir.Length + 1);
    
            try
            {
                // Will not overwrite if the destination file already exists.
                File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
            }
    
            // Catch exception if the file was already copied.
            catch (IOException copyError)
            {
                Console.WriteLine(copyError.Message);
            }
        }
    
        // Delete source files that were copied.
        foreach (string f in txtList)
        {
            File.Delete(f);
        }
        foreach (string f in picList)
        {
            File.Delete(f);
        }
    }
    
    catch (DirectoryNotFoundException dirNotFound)
    {
        Console.WriteLine(dirNotFound.Message);
    }
    View Code

     7.3 File.Move 方法 —— 将指定文件移到新位置,并提供指定新文件名的选项。 

    public static void Move(string sourceFileName,string destFileName)
    using System;
    using System.IO;
    
    class Test 
    {
        public static void Main() 
        {
            string path = @"c:	empMyTest.txt";
            string path2 = @"c:	emp2MyTest.txt";
            try 
            {
                if (!File.Exists(path)) 
                {
                    // This statement ensures that the file is created,
                    // but the handle is not kept.
                    using (FileStream fs = File.Create(path)) {}
                }
    
                // Ensure that the target does not exist.
                if (File.Exists(path2))    
                File.Delete(path2);
    
                // Move the file.
                File.Move(path, path2);
                Console.WriteLine("{0} was moved to {1}.", path, path2);
    
                // See if the original exists now.
                if (File.Exists(path)) 
                {
                    Console.WriteLine("The original file still exists, which is unexpected.");
                } 
                else 
                {
                    Console.WriteLine("The original file no longer exists, which is expected.");
                }            
    
            } 
            catch (Exception e) 
            {
                Console.WriteLine("The process failed: {0}", e.ToString());
            }
        }
    }
    View Code

     7.4 File.Delete 方法 ——删除指定的文件。

      public static void Delete(string path)

    string sourceDir = @"c:current";
    string backupDir = @"c:archives2008";
    
    try
    {
        string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
        string[] txtList = Directory.GetFiles(sourceDir, "*.txt");
    
        // Copy picture files.
        foreach (string f in picList)
        {
            // Remove path from the file name.
            string fName = f.Substring(sourceDir.Length + 1);
    
            // Use the Path.Combine method to safely append the file name to the path.
            // Will overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
        }
    
        // Copy text files.
        foreach (string f in txtList)
        {
    
            // Remove path from the file name.
            string fName = f.Substring(sourceDir.Length + 1);
    
            try
            {
                // Will not overwrite if the destination file already exists.
                File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
            }
    
            // Catch exception if the file was already copied.
            catch (IOException copyError)
            {
                Console.WriteLine(copyError.Message);
            }
        }
    
        // Delete source files that were copied.
        foreach (string f in txtList)
        {
            File.Delete(f);
        }
        foreach (string f in picList)
        {
            File.Delete(f);
        }
    }
    
    catch (DirectoryNotFoundException dirNotFound)
    {
        Console.WriteLine(dirNotFound.Message);
    }
    View Code
  • 相关阅读:
    25-javaweb接入支付宝支付接口
    4-js 函数
    24-filter-拦截器
    23-新建maven 项目
    22-maven-安装与配置
    15-matlab矩阵运用
    2018.7.18 div,section,article的区别和使用
    2018.7.17 牛客网训练
    2018.7.16常用推荐算法
    2018.7.15 解决css中input输入框点击时去掉外边框方法
  • 原文地址:https://www.cnblogs.com/v10258/p/3191168.html
Copyright © 2020-2023  润新知