现在的位置: 首页 > 综合 > 正文

C#文件操作

2018年04月03日 ⁄ 综合 ⁄ 共 32126字 ⁄ 字号 评论关闭

一、文件系統概述

    计算机系统的重要作用之一是能快速处理大量信息,因此数据的组织和存取成为一个极为重要的内容。文件是信息的一种组织形式,而文件系统的的目标就是提高存储器的利用率,接受用户的委托实施对文件的操作。

      文件系统是操作系统的一个重要组成部分。文件系统所要解决的问题包括:管理存储设置,决定文件的存放位置和方式,提供共享能力,保证文件安全性,提供友好的用户接口。通过文件系统,用户和应用程序能方便地进行数据存储,而不必关心底层存储设备的实现。

     Windows支持多种文件系统,如FAT,FAT32,NTFS等。这些文件系统在操作系统内部有不同的实现方式,然而它们提供给用户的接口是一致的。如果应用程序不涉及到操作系统的具体特性,那么只要按照标准式来编写代码,生成的应用程序就可以运行在各个文件系统上,甚至还可以不经改动移植到其他操作系统(比如Unix和Linux)上.NET框架中的IO处理部分就封装了文件系统的实现细节,提供给开发人员一个标准化的接口。

     Windows操作系统对文件系统采用多级目录结构,并且提供了一组命令用于文件和目录管理。可以使用.NET提供的标准方法进行目录管理、文件控制和文件存取等工作,程序代友编译执行时,.NET框架会自动调用相关的系统命令。

     C#将文件视为一个字节序列,以流的方式对文件进行操作。流是字节序列的制作概念,文件、输入/输出设计、内部时行程序管道以及TCP/IP套接字等都可以视为一个流。.NET对流的概念进行了抽象,为这些不同类型的输入和输出提供了统一的视图,使程序员不必去了解操作系统和基础设备的具体细节。

二、目录和文件

1. 相关枚举类型

a) FileAccess,该枚举类型表示文件的访问权限,可以为以下值。

i. Read---对文件拥有读权限

ii. ReadWrite---对文件拥有的读写权限

iii. Write---对文件拥有写权限

b) FileAttributes,该枚举类型表示文件的类型

i. Archive---存档文件

ii. Compressed---压缩文件

iii. Device---设备文件

iv. Directory---目录

v. Encrypted---加密文件

vi. Hidden---隐藏文件

vii. Normal---普通文件

viii. NOtContentIndexd---无索引文件

ix. Offline---脱机文件

x. ReadOnly---只读文件

xi. ReparsePoint---重分析文件

xii. SparseFile---稀疏文件

xiii. System---系统文件

xiv. Temporary---临时文件

枚举值可以按位进行组合使用,比如FileAttributes.System|FileAttributes.ReadOnly表示系统只读文件。当然,一些相互排斥的类型是不能进行组合的,比如一个文件不能既是普通文件,又是隐藏文件。

c) FileMode,该枚举类型表示文件的打开方式,可以为以下值:

i. Append---以追加的方式打开文件,如果文件存在则移动到文件末尾,否则创建一个新文件。

ii. Create---创建并打开一个文件,如果文件已经存在则覆盖旧文件。

iii. Open---打开现有文件,如果文件不存在发生异常。

iv. OpenOrCreate---打开或新建一个文件,如果文件存在则打开它,否则创建并打开一个新文件。

v. Truncate---打开现有文件,并清空文件内容。

d) FileShare,该枚举类型表示文件共享方式,可以为以下值。

i. None---禁止任何形式的共享。

ii. Read---读共享,打开文件后允许其它进程对文件进行读写操作。

iii. ReadWrite---读写共享,打开文件后允许其它进程对文件进行读和写操作。

iv. Write---写共享,打开文件后允许其它进程对文件进行写操作。

e) SeekOrigin,该枚举类型表示文件的偏移以什么为准,可以为以下值:

i. Begin---从文件起始位置计。

ii. Current---从文件流的当前位置计。

iii. End---从文件流的末尾位置计。

f) NotifyFilters,该枚举类型用于指定对文件或目录哪些属性的修改进行监视,可以为以下值:

i. Attributes---对属性的变化进行监视。

ii. CreationTime---对创建时间的变化进行监视。

iii. DirectoryName---对目录名称的变化进行监视。

iv. FileName---对文件名称的变化进行监视。

v. LastAccess---对最后一次访问时间的变化进行监视。

vi. LastWrite---对最后一次时间的变化进行监视。

vii. Security---对安全设置的变化进行监视。

viii. Size---对大小的变化进行监视。

2. 目录

使用Directory类提供的目录管理功能,不仅可以创建、移动和删除目录,还可以获取和设置目录的相关信息。

Directory提供的静态方法有:

Ø Public static DirectoryInfo CreateDirectory(string)---给定路径名,创建目录,并返回目录信息。

Ø Public static void Delete(string)---给定路径名,删除目录。

Ø Public static void bool Exists(string)----给定路径名,判断目录是否存在。

Ø Public static DateTime GetCreationTime(string)----给定路径名,获取目录创建的日期和时间。

Ø Public static string GetCurrentDirectory()---获取应用程序的当前工作目录。

Ø Public static string[] GetDirectory(string)---给定路径名,获取目录中的子目录列表。

Ø Public static string GetDirectoryRoot(string)---给定路径名,获取目录的卷信息或要信息。

Ø Public static string[] GetFile(string)---给定路径名,获取目录中的文件列表。

Ø Public static string[] GetFileSystemEntries(string)---给定路径名,获取目录中的子目录和文件列表。

Ø Public static DateTime GetLastAccessTime(string)---给定路径名,获取文件最近一次访问的日期和时间。

Ø Public static DateTime GetlastWriteTime(string)---给定路径名,获得目录最近一次修改的日期和时间。

Ø Public static string[] GetLogicalDrivers()---获得计算机上的逻辑驱动器列表。

Ø Public static DirectoryInfo GetParent(string)---给定路径名,获取目录上层目录的信息。

Ø Public static void Move(string,string)---给定源路径名和目标路径名,移动目录。

Ø Public static void SetCreationTime(string,DateTime)---给定路径名,设置目录创建的日期和时间。

Ø Public static void SetCreationDirectory(string)---给定路径名,将目录设置为应用程序的当前工作目录。

Ø Public static void SetLastAccessTime(string,DateTime)---给定路径名,设置目录最近一次被访问的日期和时间。

Ø Public static void SetLastWriteTime(string,DateTime)---给定路径名,设置目录最近一次被修改的日期和时间。

3. 文件

a) 文件基本操作

Ø Public static FileStream Create(string)---给定文件路径名,创建文件,并返回一个FileStream流对象。

Ø Public static StreamWriter CreateText(string)---给定文件路径名,以文本的方式创建文件,并返回一个StreamWriter流对象。

Ø Public static void Copy(string,string)---给定源路径名和目录路径名,考贝文件。

Ø Public static void Move(string,string)---给定源路径名和目录路径名,移支文件。

Ø Public static void Delete(string)---给定源路径名和目录路径名,删除文件。

Ø Public static void Exists(string)---给定源路径名和目录路径名,判断文件是否存在。

b)获取和设置文件信息

Ø Public static FileAttributes GetAttributes(string)------给定源路径名,获取文件的属性集。

Ø Public static DateTime GetCreationTime(string)---给定文件路径名,获取文件创建宾日期和时间。

Ø Public static DateTime GetLastAccessTime(string)---给定文件路径名,获得文件最近一次被访问的日期和时间。

Ø Public static DateTime GetLastWriteTime(string)---给定文件路径名,获得文件最近一次被修改的日期和时间。

Ø Public static void SetAttributes(string,FileAttributes)---给定文件路径名,设置文件属性集。

Ø Public static void SetCreationTime(string,DateTime)---给定文件路径名,设置文件创建的日期和时间。

Ø Public static void SetLastAccessTime(string,DateTime)----给定文件路径名,设置文件最近一次被访问的日期和时间。

Ø Public static void SetLastWriteTime(string,DateTime)---给定文件路径名,设置文件最后一次被修改的日期和时间。

c)打开文件,并将文件与流对象相关联

Ø Public static FileStream Open(string,FileMode)---给定文件路径名,按指定的方式打开文件,并返回一个FileStream流对象。

Ø Public static FileStream OpenRead(string)---给定文件路径名,以只读方式打开文件,并返回一个FileStream流对象。

Ø Public static FileStream OpenWrite(string)---给定文件路径名,打开文件进行读写操作,并返回一个FileStream流对象。

Ø Public static StreamReader OpenText(string)---给定文件路径名,以文本方式打开文件并返回一个FileStream流对象。

Ø Public static StreamWriter AppendText(string)---给定文件路径名,以文本方式打开文件进行写操作,并返回一个StreamWriter流对象。

 

一、创建目录列表

   下面的代码示例演示如何使用 I/O 类来创建目录中具有“.exe”扩展名的所有文件的列表。

using System;

using System.IO;

class DirectoryLister

{

    public static void Main(String[] args)

    {

        string path = ".";

        if (args.Length > 0)

        {

            if (File.Exists(args[0])

            {

                path = args[0];

            }

            else

            {

                Console.WriteLine("{0} not found; using current directory:",

                    args[0]);

            }

       

        DirectoryInfo dir = new DirectoryInfo(path);

        foreach (FileInfo f in dir.GetFiles("*.exe"))

        {

            String name = f. Name;

            long size = f.Length;

            DateTime creationTime = f.CreationTime;

            Console.WriteLine("{0,-12:N0} {1,-20:g} {2}", size,

                creationTime, name);

        }

    }

}

在本示例中,DirectoryInfo 是当前目录,用 (".") 表示,代码列出了当前目录中具有 .exe 扩展名的所有文件,同时还列出了这些文件的大小、创建时间和名称。假设 C:/MyDir 的 /Bin 子目录中存在多个 .exe 文件,此代码的输出可能如下所示:

953          7/20/2000 10:42 AM   C:/MyDir/Bin/paramatt.exe

664          7/27/2000 3:11 PM    C:/MyDir/Bin/tst.exe

403          8/8/2000 10:25 AM    C:/MyDir/Bin/dirlist.exe

二、对新建的数据文件进行读取和写入

BinaryWriter 和 BinaryReader 类用于读取和写入数据,而不是字符串。下面的代码示例演示如何向新的空文件流 (Test.data) 写入数据及从中读取数据。在当前目录中创建了数据文件之后,也就同时创建了相关的BinaryWriter
BinaryReaderBinaryWriter用于向 Test.data 写入整数 0 到 10,Test.data 将文件指针置于文件尾。在将文件指针设置回初始位置后,BinaryReader读出指定的内容。

using System;

using System.IO;

class MyStream

{

    private const string FILE_NAME = "Test.data";

    public static void Main(String[] args)

    {

        // Create the new, empty data file.

        if (File.Exists(FILE_NAME))

        {

            Console.WriteLine("{0} already exists!", FILE_NAME);

            return;

        }

        FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew);

        // Create the writer for data.

        BinaryWriter w = new BinaryWriter(fs);

        // Write data to Test.data.

        for (int i = 0; i < 11; i++)

        {

            w.Write( (int) i);

        }

        w.Close();

        fs.Close();

        // Create the reader for data.

        fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);

        BinaryReader r = new BinaryReader(fs);

        // Read data from Test.data.

        for (int i = 0; i < 11; i++)

        {

            Console.WriteLine(r.ReadInt32());

        }

        r.Close();

        fs.Close();

    }

}

注意:如果 Test.data 已存在于当前目录中,则引发一个 IOException。始终使用 FileMode.Create 创建新文件,而不引发IOException

三、打开并追加到日志文件

    StreamWriter 和 StreamReader 向流写入字符并从流读取字符。下面的代码示例打开 log.txt 文件(如果文件不存在则创建文件)以进行输入,并将信息附加到文件尾。然后将文件的内容写入标准输出以便显示。除此示例演示的做法外,还可以将信息存储为单个字符串或字符串数组,WriteAllText 或 WriteAllLines 方法可以用于实现相同的功能。

using System;

using System.IO;

class DirAppend

{

    public static void Main(String[] args)

    {

        using (StreamWriter w = File.AppendText("log.txt"))

        {

            Log ("Test1", w);

            Log ("Test2", w);

            // Close the writer and underlying file.

            w.Close();

        }

        // Open and read the file.

        using (StreamReader r = File.OpenText("log.txt"))

        {

            DumpLog (r);

        }

    }

    public static void Log (String logMessage, TextWriter w)

    {

        w.Write("/r/nLog Entry : ");

        w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),

            DateTime.Now.ToLongDateString());

        w.WriteLine("  :");

        w.WriteLine("  :{0}", logMessage);

        w.WriteLine ("-------------------------------");

        // Update the underlying file.

        w.Flush();

    }

    public static void DumpLog (StreamReader r)

    {

        // While not at the end of the file, read and write lines.

        String line;

        while ((line=r.ReadLine())!=null)

        {

            Console.WriteLine(line);

        }

        r.Close();

    }

}

四、从文件读取文本

下面的代码示例演示如何从文本文件中读取文本。第二个示例在检测到文件结尾时向您发出通知。通过使用 ReadAll 或 ReadAllText 方法也可以实现此功能。

代码一:

using System;

using System.IO;

class Test

{

    public static void Main()

    {

        try

        {

            // Create an instance of StreamReader to read from a file.

            // The using statement also closes the StreamReader.

            using (StreamReader sr = new StreamReader("TestFile.txt"))

            {

                String line;

                // Read and display lines from the file until the end of

                // the file is reached.

                while ((line = sr.ReadLine()) != null)

                {

                    Console.WriteLine(line);

                }

            }

        }

        catch (Exception e)

        {

            // Let the user know what went wrong.

            Console.WriteLine("The file could not be read:");

            Console.WriteLine(e.Message);

        }

    }

}

代码二:

using System;

using System.IO;

public class TextFromFile

{

    private const string FILE_NAME = "MyFile.txt";

    public static void Main(String[] args)

    {

        if (!File.Exists(FILE_NAME))

        {

            Console.WriteLine("{0} does not exist.", FILE_NAME);

            return;

        }

        using (StreamReader sr = File.OpenText(FILE_NAME))

        {

            String input;

            while ((input=sr.ReadLine())!=null)

            {

                Console.WriteLine(input);

            }

            Console.WriteLine ("The end of the stream has been reached.");

            sr.Close();

        }

    }

注意:此代码通过调用 File.OpenText 创建一个指向 MyFile.txt 的 StreamReader。StreamReader.ReadLine 将每一行都作为一个字符串返回。当不再有要读取的字符时,会有一条消息显示该情况,然后流关闭。

五、向文件写入文本

下面的代码示例演示如何向文本文件中写入文本。

第一个示例演示如何向现有文件中添加文本。第二个示例演示如何创建一个新文本文件并向其中写入一个字符串。WriteAllText 方法可提供类似的功能。

代码一:

using System;

using System.IO;

class Test

{

    public static void Main()

    {

        // Create an instance of StreamWriter to write text to a file.

        // The using statement also closes the StreamWriter.

        using (StreamWriter sw = new StreamWriter("TestFile.txt"))

        {

            // Add some text to the file.

            sw.Write("This is the ");

            sw.WriteLine("header for the file.");

            sw.WriteLine("-------------------");

            // Arbitrary objects can also be written to the file.

            sw.Write("The date is: ");

            sw.WriteLine(DateTime.Now);

        }

    }

}

代码二:

using System;

using System.IO;

public class TextToFile

{

    private const string FILE_NAME = "MyFile.txt";

    public static void Main(String[] args)

    {

        if (File.Exists(FILE_NAME))

        {

            Console.WriteLine("{0} already exists.", FILE_NAME);

            return;

        }

        using (StreamWriter sw = File.CreateText(FILE_NAME))

        {

            sw.WriteLine ("This is my file.");

            sw.WriteLine ("I can write ints {0} or floats {1}, and so on.",

                1, 4.2);

            sw.Close();

        }

    }

}

六、从字符串中读取字符

下面的代码示例允许您在现有字符串中从指定的位置开始读取一定数目的字符。使用 StringReader 完成此操作,如下所示。

此代码定义字符串并将其转换为字符数组,然后,可以使用适当的 StringReader.Read 方法读取该字符数组。

本示例只从字符串中读取指定数目的字符,如下所示。

Some number o

代码:

using System;

using System.IO;

public class CharsFromStr

{

    public static void Main(String[] args)

    {

        // Create a string to read characters from.

        String str = "Some number of characters";

        // Size the array to hold all the characters of the string

        // so that they are all accessible.

        char[] b = new char[24];

        // Create an instance of StringReader and attach it to the string.

        StringReader sr = new StringReader(str);

        // Read 13 characters from the array that holds the string, starting

        // from the first array member.

        sr.Read(b, 0, 13);

        // Display the output.

        Console.WriteLine(b);

        // Close the StringReader.

        sr.Close();

    }

}

七、向字符串写入字符

下面的代码示例把从字符数组中指定位置开始的一定数目的字符写入现有的字符串。使用 StringWriter 完成此操作,如下所示。

代码:

using System;

using System.IO;

using System.Text;

public class CharsToStr

{

    public static void Main(String[] args)

    {

        // Create an instance of StringBuilder that can then be modified.

        StringBuilder sb = new StringBuilder("Some number of characters");

        // Define and create an instance of a character array from which

        // characters will be read into the StringBuilder.

        char[] b = {' ','t','o',' ','w','r','i','t','e',' ','t','o','.'};

        // Create an instance of StringWriter

        // and attach it to the StringBuilder.

        StringWriter sw = new StringWriter(sb);

        // Write three characters from the array into the StringBuilder.

        sw.Write(b, 0, 3);

        // Display the output.

        Console.WriteLine(sb);

        // Close the StringWriter.

        sw.Close();

    }

}

此示例阐释了使用 StringBuilder 来修改现有的字符串。请注意,这需要一个附加的
using 声明,因为 StringBuilder
类是 System.Text 命名空间的成员。另外,这是一个直接创建字符数组并对其进行初始化的示例,而不是定义字符串然后将字符串转换为字符数组。

此代码产生以下输出:

Some number of characters to

八、打开一个现有文件或创建一个文件,将文本追加到此文件并显示结果

using System;

using System.IO;

public class FileInfoMainTest

{

    public static void Main()

    {

        // Open an existing file, or create a new one.

        FileInfo fi = new FileInfo("temp.txt");

        // Create a writer, ready to add entries to the file.

        StreamWriter sw = fi.AppendText();

        sw.WriteLine("This is a new entry to add to the file");

        sw.WriteLine("This is yet another line to add...");

        sw.Flush();

        sw.Close();

        // Get the information out of the file and display it.

        StreamReader sr = new StreamReader( fi.OpenRead() );

        while (sr.Peek() != -1)

            Console.WriteLine( sr.ReadLine() );

    }

}

九、创建两个文件,并接着对其进行写入、读取、复制和删除操作

using System;

using System.IO;

class Test

{

    public static void Main()

    {

        string path = @"c:/temp/MyTest.txt";

        FileInfo fi1 = new FileInfo(path);

        if (!fi1.Exists)

        {

            //Create a file to write to.

            using (StreamWriter sw = fi1.CreateText())

            {

                sw.WriteLine("Hello");

                sw.WriteLine("And");

                sw.WriteLine("Welcome");

            }

        }

        //Open the file to read from.

        using (StreamReader sr = fi1.OpenText())

        {

            string s = "";

            while ((s = sr.ReadLine()) != null)

            {

                Console.WriteLine(s);

            }

        }

        try

        {

            string path2 = path + "temp";

            FileInfo fi2 = new FileInfo(path2);

            //Ensure that the target does not exist.

            fi2.Delete();

            //Copy the file.

            fi1.CopyTo(path2);

            Console.WriteLine("{0} was copied to {1}.", path, path2);

            //Delete the newly created file.

            fi2.Delete();

            Console.WriteLine("{0} was successfully deleted.", path2);

        }

        catch (Exception e)

        {

            Console.WriteLine("The process failed: {0}", e.ToString());

        }

    }

}

十、移动一个文件

代码一:

using System;

using System.IO;

class Test

{

    public static void Main()

    {

        string path = @"c:/temp/MyTest.txt";

        string path2 = @"c:/temp2/MyTest.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());

        }

    }

}

十一、如何将一个文件移动至另一位置并重命名该文件

using System;

using System.Runtime.CompilerServices;

using System.Runtime.InteropServices;

using System.IO;

using System.Reflection;

using System.Security.Permissions;

using System.Text;

using System.Text.RegularExpressions;

using System.Xml;

namespace Microsoft.Samples.MoveTo.CS

{

class Program

{

  private static string sourcePath = Environment.GetFolderPath

   (Environment.SpecialFolder.MyDocuments) +

   @"/FileInfoTestDirectory/MoveFrom/FromFile.xml";

 

  private static string destPath = Environment.GetFolderPath

   (Environment.SpecialFolder.MyDocuments) +

   @"/FileInfoTestDirectory/DestFile.xml";

  //

  // The main entry point for the application.

  //

  [STAThread()] static void Main ()

  {

   // Change Console properties to make it obvious that

   // the application is starting.

   Console.Clear();

   // Move it to the upper left corner of the screen.

   Console.SetWindowPosition(0, 0);

   // Make it very large.

   Console.SetWindowSize(Console.LargestWindowWidth - 24,

    Console.LargestWindowHeight - 16);

   Console.WriteLine("Welcome.");

   Console.WriteLine("This application demonstrates the FileInfo.MoveTo method.");

   Console.WriteLine("Press any key to start.");

   string s = Console.ReadLine();

   Console.Write("    Checking whether ");

   Console.Write(sourcePath);

   Console.WriteLine(" exists.");

   FileInfo fInfo = new FileInfo (sourcePath);

   EnsureSourceFileExists();

   DisplayFileProperties(fInfo);

   Console.WriteLine("Preparing to move the file to ");

   Console.Write(destPath);

   Console.WriteLine(".");

   MoveFile(fInfo);

   DisplayFileProperties(fInfo);

   Console.WriteLine("Preparing to delete directories.");

   DeleteFiles();

   Console.WriteLine("Press the ENTER key to close this application.");

   s = Console.ReadLine();

  }

  //

  // Moves the supplied FileInfo instance to destPath.

  //

  private static void MoveFile(FileInfo fInfo)

  {

   try

   {

    fInfo.MoveTo(destPath);

    Console.WriteLine("File moved to ");

    Console.WriteLine(destPath);

   } catch (Exception ex) {

    DisplayException(ex);

   }

  }

  //

  // Ensures that the test directories

  // and the file FromFile.xml all exist.

  //

  private static void EnsureSourceFileExists()

  {

   FileInfo fInfo = new FileInfo(sourcePath);

   string dirPath = fInfo.Directory.FullName;

   if (!Directory.Exists(dirPath))

   {

    Directory.CreateDirectory(dirPath);

   }

   if (File.Exists(destPath))

   {

    File.Delete(destPath);

   }

   Console.Write("Creating file ");

   Console.Write(fInfo.FullName);

   Console.WriteLine(".");

   try

   {

    if (!fInfo.Exists)

    {

     Console.WriteLine("Adding data to the file.");

     WriteFileContent(10);

     Console.WriteLine("Successfully created the file.");

    }

   }

   catch (Exception ex)

   {

    DisplayException(ex);

   }

   finally

   {

    dirPath = null;

   }

  }

  //

  // Creates and saves an Xml file to sourcePath.

  //

  private static void WriteFileContent(int totalElements)

  {

   XmlDocument doc = new XmlDocument();

   doc.PreserveWhitespace = true;

   doc.AppendChild(doc.CreateXmlDeclaration("1.0", null, "yes"));

   doc.AppendChild(doc.CreateWhitespace("/r/n"));

   XmlElement root = doc.CreateElement("FileInfo.MoveTo");

   root.AppendChild(doc.CreateWhitespace("/r/n"));

   int index = 0;

   XmlElement elem;

   while (index < totalElements)

   {

   

    elem = doc.CreateElement("MyElement");

    elem.SetAttribute("Index", index.ToString());

    elem.AppendChild(doc.CreateWhitespace("/r/n"));

    elem.AppendChild(doc.CreateTextNode(String.Format

     ("MyElement at position {0}.", index)));

    elem.AppendChild(doc.CreateWhitespace("/r/n"));

    root.AppendChild(elem);

    root.AppendChild(doc.CreateWhitespace("/r/n"));

    index++;

   }

   doc.AppendChild(root);

   doc.AppendChild(doc.CreateWhitespace("/r/n"));

   doc.Save(sourcePath);

   elem = null;

   root = null;

   doc = null;

  }

  //

  // Displays FullName, CreationTime, and LastWriteTime of the supplied

  // FileInfo instance, then displays the text of the file.

  //

  private static void DisplayFileProperties(FileInfo fInfo)

  {

   Console.WriteLine("The FileInfo instance shows these property values.");

   StreamReader reader = null;

   try

   {

    Console.Write("FullName: ");

    Console.WriteLine(fInfo.FullName);

    Console.Write("CreationTime: ");

    Console.WriteLine(fInfo.CreationTime);

    Console.Write("LastWriteTime: ");

    Console.WriteLine(fInfo.LastWriteTime);

    Console.WriteLine();

    Console.WriteLine("File contents:");

    Console.WriteLine();

    reader = new StreamReader(fInfo.FullName);

    while (!reader.EndOfStream)

    {

     Console.WriteLine(reader.ReadLine());

    }

    Console.WriteLine();

   }

   catch (Exception ex)

   {

    DisplayException(ex);

   }

   finally

   {

    if (reader != null)

    {

     reader.Close();

    }

    reader = null;

   }

  }

  //

  // Deletes the test directory and all its files and subdirectories.

  //

  private static void DeleteFiles()

  {

   try

   {

    DirectoryInfo dInfo = new DirectoryInfo(Environment.GetFolderPath

     (Environment.SpecialFolder.MyDocuments) + "//FileInfoTestDirectory");

    if (dInfo.Exists)

    {

     dInfo.Delete(true);

     Console.WriteLine("Successfully deleted directories and files.");

    }

    dInfo = null;

   }

   catch (Exception ex)

   {

    DisplayException(ex);

   }

  }

  //

  // Displays information about the supplied Exception. This

  // code is not suitable for production applications.

  //

  private static void DisplayException(Exception ex)

  {

   StringBuilder sb = new StringBuilder();

   sb.Append("An exception of type /"");

   sb.Append(ex.GetType().FullName);

   sb.Append("/" has occurred./r/n");

   sb.Append(ex.Message);

   sb.Append("/r/nStack trace information:/r/n");

   MatchCollection matchCol = Regex.Matches(ex.StackTrace,

@"(at/s)(.+)(/.)([^/.]*)(/()([^/)]*)(/))((/sin/s)(.+)(:line )([/d]*))?");

   int L = matchCol.Count;

   string[] argList;

   Match matchObj;

   int y, K;

   for(int x = 0; x < L; x++)

   {

    matchObj = matchCol[x];

    sb.Append(matchObj.Result("/r/n/r/n$1 $2$3$4$5"));

    argList = matchObj.Groups[6].Value.Split(new char[] { ',' });

    K = argList.Length;

    for (y = 0; y < K; y++)

    {

     sb.Append("/r/n    ");

     sb.Append(argList[y].Trim().Replace(" ", "        "));

     sb.Append(',');

    }

    sb.Remove(sb.Length - 1, 1);

    sb.Append("/r/n)");

    if (0 < matchObj.Groups[8].Length)

    {

     sb.Append(matchObj.Result("/r/n$10/r/nline $12"));

    }

   }

   argList = null;

   matchObj = null;

   matchCol = null;

   Console.WriteLine(sb.ToString());

   sb = null;

  }

}

}

十二、指定的路径删除一个文件

代码一:

using System;

using System.IO;

class Test

{

    public static void Main()

    {

        string path = @"c:/temp/MyTest.txt";

        try

        {

            using (StreamWriter sw = File.CreateText(path)) {}

            string path2 = path + "temp";

            // Ensure that the target does not exist.

            File.Delete(path2);

            // Copy the file.

            File.Copy(path, path2);

            Console.WriteLine("{0} was copied to {1}.", path, path2);

            // Delete the newly created file.

            File.Delete(path2);

            Console.WriteLine("{0} was successfully deleted.", path2);

        }

        catch (Exception e)

        {

            Console.WriteLine("The process failed: {0}", e.ToString());

        }

    }

}

代码二:

using System;

using System.IO;

class Test

{

    public static void Main()

    {

        string path = @"c:/temp/MyTest.txt";

        FileInfo fi1 = new FileInfo(path);

        try

        {

            using (StreamWriter sw = fi1.CreateText()) {}

            string path2 = path + "temp";

            FileInfo fi2 = new FileInfo(path2);

            //Ensure that the target does not exist.

            fi2.Delete();

            //Copy the file.

            fi1.CopyTo(path2);

            Console.WriteLine("{0} was copied to {1}.", path, path2);

            //Delete the newly created file.

            fi2.Delete();

            Console.WriteLine("{0} was successfully deleted.", path2);

        }

        catch (Exception e)

        {

            Console.WriteLine("The process failed: {0}", e.ToString());

        }

    }

}

十三、将文件复制到指定路径,不允许改写同名的目标文件

using System;

using System.IO;

class Test

{

    public static void Main()

    {

        string path = @"c:/temp/MyTest.txt";

        string path2 = path + "temp";

        try

        {

            using (FileStream fs = File.Create(path)) {}

            // Ensure that the target does not exist.

            File.Delete(path2);

            // Copy the file.

            File.Copy(path, path2);

            Console.WriteLine("{0} copied to {1}", path, path2);

            // Try to copy the same file again, which should fail.

            File.Copy(path, path2);

            Console.WriteLine("The second Copy operation succeeded, which was not expected.");

        }

        catch (Exception e)

        {

            Console.WriteLine("Double copying is not allowed, as expected.");

            Console.WriteLine(e.ToString());

        }

    }

}

十四、将文件复制到指定路径,允许改写同名的目标文件

using System;

using System.IO;

class Test

{

    public static void Main()

    {

        string path = @"c:/temp/MyTest.txt";

        string path2 = path + "temp";

        try

        {

            // Create the file and clean up handles.

            using (FileStream fs = File.Create(path)) {}

            // Ensure that the target does not exist.

            File.Delete(path2);

            // Copy the file.

            File.Copy(path, path2);

            Console.WriteLine("{0} copied to {1}", path, path2);

            // Try to copy the same file again, which should succeed.

            File.Copy(path, path2, true);

            Console.WriteLine("The second Copy operation succeeded, which was expected.");

        }

        catch

        {

            Console.WriteLine("Double copy is not allowed, which was not expected.");

        }

    }

}

十五、演示了FileInfo类的 CopyTo方法的两个重载

using System;

using System.IO;

class Test

{

    public static void Main()

    {

        string path = @"c:/temp/MyTest.txt";

        string path2 = @"c:/temp/MyTest.txt" + "temp";

        FileInfo fi1 = new FileInfo(path);

        FileInfo fi2 = new FileInfo(path2);

        try

        {

            // Create the file and clean up handles.

            using (FileStream fs = fi1.Create()) {}

            //Ensure that the target does not exist.

            fi2.Delete();

            //Copy the file.

            fi1.CopyTo(path2);

            Console.WriteLine("{0} was copied to {1}.", path, path2);

            //Try to copy it again, which should succeed.

            fi1.CopyTo(path2, true);

            Console.WriteLine("The second Copy operation succeeded, which is expected.");

        }

        catch

        {

            Console.WriteLine("Double copying was not allowed, which is not expected.");

        }

    }

}

十六、如何将一个文件复制到另一文件,指定是否改写已存在的文件

using System;

using System.IO;

public class CopyToTest

{

    public static void Main()

    {

        // Create a reference to a file, which might or might not exist.

        // If it does not exist, it is not yet created.

        FileInfo fi = new FileInfo("temp.txt");

        // Create a writer, ready to add entries to the file.

        StreamWriter sw = fi.AppendText();

        sw.WriteLine("Add as many lines as you like...");

        sw.WriteLine("Add another line to the output...");

        sw.Flush();

        sw.Close();

        // Get the information out of the file and display it.

        StreamReader sr = new StreamReader( fi.OpenRead() );

        Console.WriteLine("This is the information in the first file:");

        while (sr.Peek() != -1)

            Console.WriteLine( sr.ReadLine() );

        // Copy this file to another file. The true parameter specifies

        // that the file will be overwritten if it already exists.

        FileInfo newfi = fi.CopyTo("newTemp.txt", true);

        // Get the information out of the new file and display it.

        sr = new StreamReader( newfi.OpenRead() );

        Console.WriteLine("{0}This is the information in the second file:", Environment.NewLine);

        while (sr.Peek() != -1)

            Console.WriteLine( sr.ReadLine() );

    }

}

十七、显示指定文件的大小

// The following example displays the names and sizes

// of the files in the specified directory.

using System;

using System.IO;

public class FileLength

{

    public static void Main()

    {

        // Make a reference to a directory.

        DirectoryInfo di = new DirectoryInfo("c://");

        // Get a reference to each file in that directory.

        FileInfo[] fiArr = di.GetFiles();

        // Display the names and sizes of the files.

        Console.WriteLine("The directory {0} contains the following files:", di.Name);

        foreach (FileInfo f in fiArr)

            Console.WriteLine("The size of {0} is {1} bytes.", f.Name, f.Length);

    }

}

十八、通过将 Archive
Hidden 属性应用于文件,演示了 GetAttributes
SetAttributes 方法。

using System;

using System.IO;

using System.Text;

class Test

{

    public static void Main()

    {

        string path = @"c:/temp/MyTest.txt";

        // Delete the file if it exists.

        if (!File.Exists(path))

        {

            File.Create(path);

        }

        if ((File.GetAttributes(path) & FileAttributes.Hidden) == FileAttributes.Hidden)

        {

            // Show the file.

            File.SetAttributes(path, FileAttributes.Archive);

            Console.WriteLine("The {0} file is no longer hidden.", path);

        }

        else

        {

            // Hide the file.

            File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);

            Console.WriteLine("The {0} file is now hidden.", path);

        }

    }

}

十九、使用 Exists
方法帮助确保文件不被改写

using System;

using System.IO;

class Test

{

    public static void Main()

    {

        string path = @"c:/temp/MyTest.txt";

        string path2 = path + "temp";

        try

        {

            using (StreamWriter sw = File.CreateText(path)) {}

            // Only do the Copy operation if the first file exists

            // and the second file does not.

            if (File.Exists(path))

            {

                if (File.Exists(path2))

                {

                    Console.WriteLine("The target already exists");

                }

                else

                {

                    // Try to copy the file.

                    File.Copy(path, path2);

                    Console.WriteLine("{0} was copied to {1}.", path, path2);

                }

            }

            else

            {

                Console.WriteLine("The source file does not exist.");

            }

        }

        catch

        {

            Console.WriteLine("Double copying is not allowed, as expected.");

        }

    }

}

二十、如何在基于 Windows 的桌面平台上使用 GetExtension
方法,返回文件的扩展名

string fileName = @"C:/mydir.old/myfile.ext";

string path = @"C:/mydir.old/";

string extension;

extension = Path.GetExtension(fileName);

Console.WriteLine("GetExtension('{0}') returns '{1}'",

    fileName, extension);

extension = Path.GetExtension(path);

Console.WriteLine("GetExtension('{0}') returns '{1}'",

    path, extension);

// This code produces output similar to the following:

//

// GetExtension('C:/mydir.old/myfile.ext') returns '.ext'

// GetExtension('C:/mydir.old/') returns ''

二十一、演示基于 Windows 的桌面平台上的 GetFullPath
方法,返回指定路径字符串的绝对路径。

string fileName = "myfile.ext";

string path1 = @"mydir";

string path2 = @"/mydir";

string fullPath;

fullPath = Path.GetFullPath(path1);

Console.WriteLine("GetFullPath('{0}') returns '{1}'",

    path1, fullPath);

fullPath = Path.GetFullPath(fileName);

Console.WriteLine("GetFullPath('{0}') returns '{1}'",

    fileName, fullPath);

fullPath = Path.GetFullPath(path2);

Console.WriteLine("GetFullPath('{0}') returns '{1}'",

    path2, fullPath);

// Output is based on your current directory, except

// in the last case, where it is based on the root drive

// GetFullPath('mydir') returns 'C:/temp/Demo/mydir'

// GetFullPath('myfile.ext') returns 'C:/temp/Demo/myfile.ext'

// GetFullPath('/mydir') returns 'C:/mydir'

二十二、演示 GetFileName
方法在基于 Windows 的桌面平台上的行为,返回指定路径字符串的文件名和扩展名。

string fileName = @"C:/mydir/myfile.ext";

string path = @"C:/mydir/";

string result;

result = Path.GetFileName(fileName);

Console.WriteLine("GetFileName('{0}') returns '{1}'",

    fileName, result);

result = Path.GetFileName(path);

Console.WriteLine("GetFileName('{0}') returns '{1}'",

    path, result);

// This code produces output similar to the following:

//

// GetFileName('C:/mydir/myfile.ext') returns 'myfile.ext'

// GetFileName('C:/mydir/') returns ''

二十三、演示 ChangeExtension
方法的用法,更改路径字符串的扩展名。

using System;

using System.IO;

public class PathSnippets

{

    public void ChangeExtension()

    {

        string goodFileName = @"C:/mydir/myfile.com.extension";

        string badFileName = @"C:/mydir/";

        string result;

        result = Path.ChangeExtension(goodFileName, ".old");

        Console.WriteLine("ChangeExtension({0}, '.old') returns '{1}'",

            goodFileName, result);

        result = Path.ChangeExtension(goodFileName, "");

        Console.WriteLine("ChangeExtension({0}, '') returns '{1}'",

            goodFileName, result);

        result = Path.ChangeExtension(badFileName, ".old");

        Console.WriteLine("ChangeExtension({0}, '.old') returns '{1}'",

            badFileName, result);

        // This code produces output similar to the following:

        //

        // ChangeExtension(C:/mydir/myfile.com.extension, '.old') returns 'C:/mydir/myfile.com.old'

        // ChangeExtension(C:/mydir/myfile.com.extension, '') returns 'C:/mydir/myfile.com.'

        // ChangeExtension(C:/mydir/, '.old') returns 'C:/mydir/.old'

二十四、演示 GetFileNameWithoutExtension
方法的用法,返回不具有扩展名的指定路径字符串的文件名。

string fileName = @"C:/mydir/myfile.ext";

string path = @"C:/mydir/";

string result;

result = Path.GetFileNameWithoutExtension(fileName);

Console.WriteLine("GetFileNameWithoutExtension('{0}') returns '{1}'",

    fileName, result);

result = Path.GetFileName(path);

Console.WriteLine("GetFileName('{0}') returns '{1}'",

    path, result);

// This code produces output similar to the following:

//

// GetFileNameWithoutExtension('C:/mydir/myfile.ext') returns 'myfile'

// GetFileName('C:/mydir/') returns ''

二十五、如何在基于 Windows 的桌面平台上使用 GetDirectoryName方法,返回指定路径字符串的目录信息。

string fileName = @"C:/mydir/myfile.ext";

string path = @"C:/mydir/";

string rootPath = @"C:/";

string directoryName;

   

directoryName = Path.GetDirectoryName(fileName);

Console.WriteLine("GetDirectoryName('{0}') returns '{1}'",

    fileName, directoryName);

directoryName = Path.GetDirectoryName(path);

Console.WriteLine("GetDirectoryName('{0}') returns '{1}'",

    path, directoryName);

directoryName = Path.GetDirectoryName(rootPath);

Console.WriteLine("GetDirectoryName('{0}') returns '{1}'",

    rootPath, directoryName);

/*

This code produces the following output:

GetDirectoryName('C:/mydir/myfile.ext') returns 'C:/mydir'

GetDirectoryName('C:/mydir/') returns 'C:/mydir'

GetDirectoryName('C:/') returns ''

*/

抱歉!评论已关闭.