File 类

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

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

   public static bool Exists(string path)

string curFile = @"c:\temp\test.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:\temp\MyTest.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);
}
}

  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:\temp\MyTest.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);
}
}

 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:\temp\MyTest.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);
}
}

  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:\temp\MyTest.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);
}
}

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

  public static string[] ReadAllLines(string path)

using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.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);
}
}
}

  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:\temp\MyTest.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);
}
}
}

 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:\temp\MyTest.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);
}
}

  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:\temp\MyTest.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);
}
}

 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:\temp\MyTest.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);
}
}
}

  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:\temp\MyTest.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);
}
}
}

  

 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:\temp\MyTest.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, , 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());
}
}
}

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

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

string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008"; 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 + ); // 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 + ); 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);
}

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

string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008"; 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 + ); // 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 + ); 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);
}

 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:\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());
}
}
}

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

  public static void Delete(string path)

string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008"; 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 + ); // 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 + ); 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);
}

C# File类常用方法的更多相关文章

  1. java File类常用方法

    file类常用方法 delete()删除此抽象路径名表示的文件和目录. equals()测试此抽象路径名与给定对象是否相等. exists()测试此抽象路径名表示的文件或目录是否存在. getName ...

  2. File类常用方法和枚举

    新建一个file对象: File f = new File("F:\\01.JAVA基础300集\\05_常用类\\122.File类的使用.mp4"); (文件路径也可以用&qu ...

  3. File类常用方法

    File类是IO中常用的类 先介绍几个常用的方法: public boolean canRead(),public boolean canWrite() 测试当前文件是否可读可写,若是则返回true ...

  4. Java File类常用方法及实例

    创建:createNewFile()在指定位置创建一个空文件,成功就返回true,如果已存在就不创建,然后返回false. createTempFile(String prefix, String s ...

  5. 62. File类常用方法

    为了怕混淆,先说明一些下面要出现的名词意思:例如:D:\\新建文件夹 (2)\\a.txt 和  D:\\新建文件夹 (2)\\aaaa D:\\新建文件夹 (2)   父路径    a.txt    ...

  6. I/O流——File类及使用

    I/O框架介绍 I/O是计算机输入/输出的接口.Java的核心库java.io提供了全方面的I/O接口,包括:文件系统的操作,文件读写,标准设备的输出等. File类及使用 ①   一个File类的对 ...

  7. File类

    存储在变量,数组和对象中的数据是暂时的,当程序终止时他们就会丢失.为了能够永久的保存程序中创建的数据,需要将他们存储到硬盘或光盘的文件中.这些文件可以移动,传送,亦可以被其他程序使用.由于数据存储在文 ...

  8. Java文件File类学习总结

    java.io.File类 代表文件和目录,在开发中,读取文件.生成文件.删除文件.修改文件的属性都会用到该类. 常见构造方法: public File(String pathName){} 以pat ...

  9. Java常用类之File类

    File 类: 1. java.io.File 类代表系统文件名(路径名.文件名); 2. File 类常见的构造方法: 2.1. File(String pathname):通过将给定路径名字符串转 ...

随机推荐

  1. mysql复制(高可用架构方案的基础)

    mysql复制:把一个数据库实例上所有改变复制到另外一个数据库库服务器实例的过程特点:1.没有改变就无所谓复制 ;改变是复制的根本与数据源2.所有的改变:是指可以复制全部改变,也可以复制部分改变 可以 ...

  2. kali 软件源 包含virtualbox所需头文件

    # deb cdrom:[Debian GNU/Linux 7.0 _Kali_ - Official Snapshot i386 LIVE/INSTALL Binary 20130905-08:50 ...

  3. modelform实例学习

    先来回顾下form的用法 一对多关系,form显示的是下拉框 多对多关系,form显示的是多选框 modelform的用法 modelsform的写法 from django.forms import ...

  4. 阻塞IO(blocking IO)

    在linux中,默认情况下所有的socket都是blocking,一个典型的读操作流程大概是这样: 当用户进程调用了recvfrom这个系统调用,kernel就开始了IO的第一个阶段:准备数据.对于n ...

  5. Windows + Ubuntu 双系统安装

    前言:本篇文章是对之前文章的更新,更新的主内容是把原来用手机拍摄的图片换成了虚拟机的截图,以及对磁盘划分的新的见解和一些使用感受,原本是打算删除之前的那篇Win + Ubuntu双系统的文章的,后来想 ...

  6. delphi 手电筒

    Self.CameraComponent1.TorchMode := TTorchMode.ModeOn;

  7. 解析Java反射 - invoke方法

    最近工作中涉及到获取同程火车票,大概描述为:将本地获取的发出城市,目的城市及出发时间按固定格式封装,调用接口获取可乘坐座席等级最高的火车票,接口返回数据用包含三层类封装的类接受,接受的类总共为四层,倒 ...

  8. PL/SQL查询设计器

    被微软惯坏的我,在使用PL/SQL进行oracle多表连接查询操作时候经常挠头. 今天无意间发现了PL/SQL也有查询设计器,虽然没有sqlserver的强大好用,但足够用了. 在菜单栏 工具---& ...

  9. RedHat Enterprise Linu…

    Abstract 在嵌入式开发中有宿主机和目标机之分:宿主机是执行编译.链接嵌入式软件的计算机:目标机是运行嵌入式软件的硬件平台. TFTP服务器作为工作于宿主机的软件,主要提供对目标机的主要映像文件 ...

  10. wdcp挂载数据盘为WWW以及之后出现的各种问题解决方法

    昨天晚上突然有客户反映服务器访问不了,经检查后是因为磁盘满了! 购买阿里云的ECS选择linux系统的时候会赠送20G的系统盘,通常来讲自己用的话基本够了,但是我们作为网络公司,安装了一个WDCP后给 ...