C# uses the FileInfo class to implement the method of copying files

高洛峰
Release: 2017-01-19 13:30:40
Original
1633 people have browsed it

本文所述实例为C#运用FileInfo类实现拷贝文件的方法,程序中C#首先创建一个 StreamWriter 对象 writer,它向 FileInfo 的实例 srcFile 所表示的文件追加文本,FileInfo 类的 CopyTo 方法,实现文件的拷贝。

具体实现代码如下:

using System;
using System.IO;
namespace 拷贝文件
{
 class Class1
 {
 [STAThread]
 static void Main(string[] args)
 {
  FileInfo srcFile = new FileInfo(@"E:\Temp\src.txt");
  // 创建一个 StreamWriter 对象 writer,它向 FileInfo 的实例 srcFile 所表示的文件追加文本。
  StreamWriter writer = srcFile.AppendText();
  writer.WriteLine("本实例实现文件的拷贝");
  // 清理当前编写器的所有缓冲区,并使所有缓冲数据写入基础流
  writer.Flush();
  writer.Close();
  // 创建使用 UTF8 编码、从现有文本文件中进行读取的 StreamReader
  StreamReader reader = srcFile.OpenText();
  Console.WriteLine("源文件为:");
  // Peek方法返回下一个可用字符,如果可用字符存在,则返回非负整数
  while ( reader.Peek() >= 0)
  {
  Console.WriteLine(reader.ReadLine());
  }
  FileInfo desFile = new FileInfo("E:\\Temp\\des.txt");
  // FileInfo 类的 CopyTo 方法,实现文件的拷贝
  FileInfo hello = srcFile.CopyTo("E:\\Temp\\des.txt", true);
  reader = desFile.OpenText();
  Console.WriteLine("拷贝后副本为:");
  while (reader.Peek()>= 0)
  {
  Console.WriteLine(reader.ReadLine());
  }
  reader.Close();
 }
 }
}
Copy after login

   

更多C#运用FileInfo类实现拷贝文件的方法相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template