C#文件操作

一、创建目录列表
   下面的代码示例演示如何使用 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 和 BinaryReader,BinaryWriter 用于向 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) + "http://www.cnblogs.com/liufei88866/admin/file://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 ''


*/

 
原文地址:https://www.cnblogs.com/liufei88866/p/1764218.html