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. Quartz.net 2.x 学习笔记03-使用反射加载定时任务

    将定时任务信息存储在XML文件中,使用反射加载定时任务 首先新建一个MVC的空站点,使用NuGet添加对Quartz.net和Common.Logging.Log4Net1213的引用,同时使用NuG ...

  2. Annotation之二:@Inherited注解继承情况

    @Inherited annotation类型是被标注过的class的子类所继承.类并不从它所实现的接口继承annotation,方法并不从它所重载的方法继承annotation. 子类中能否继承注解 ...

  3. PL/SQL本地远程连接数据库

    记录自己在开发中只用一次,但是容易忘记的问题,PL/SQL-ORACLE配置远程数据库访问: 1,下载PL/SQL连接工具,链接: https://pan.baidu.com/s/1kVeeLNp 密 ...

  4. git版本控制-详细操作

    - git,软件帮助使用者进行版本的管理 阶段一git 命令: git init 初始化 git config --global user.email "you@example.com&qu ...

  5. spring-cloud配置高可用eureka服务端

    spring-cloud配置eureka服务端 eureka用来发现其他程序 依赖 <?xml version="1.0" encoding="UTF-8" ...

  6. Windows环境下使用.bat安装和卸载服务

    一.Windows环境下使用.bat安装和卸载服务 win7环境 例子中“”Valwell.Dms.HttpService.exe“”为服务程序名称 安装服务 %SystemRoot%\Microso ...

  7. Python——通过斐波那契数列来理解生成器

    一.生成器(generator) 先来看看一个简单的菲波那切数列,出第一个和第二个外,任意一个数都是由前两个数相加得到的.如:0,1,1,2,3,5,8,13...... 输入斐波那契数列前N个数: ...

  8. oracle10g Error in invoking target 'install' of makefile

    oracle10g series error error in invoking target 'install' of makefile /u01/app/oracle/oracle/product ...

  9. div+css 左右两列自适应高度 ,以及父级div也跟着自适应子级的高度(兼容各大浏览器)

    <style type="text/css" media="screen"> <!-- #main {width:500px;_height: ...

  10. Django Rest Framework 3

    目录 一.版本 二.解析器 三.序列化 四.请求数据验证 一.版本 程序也来越大时,可能通过版本不同做不同的处理 没用rest_framework之前,我们可以通过以下这样的方式去获取. 1 clas ...