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. java代码求奖金。要求从键盘输入利润

    总结:看似文字描述很多, package com.ai; import java.util.Scanner; import com.b.Scaner; //v企业发放的奖金根据利润提成.利润(I)低于 ...

  2. mongdb与mysql的联系和区别

    与关系型数据库相比,MongoDB的优点:①弱一致性(最终一致),更能保证用户的访问速度举例来说,在传统的关系型数据库中,一个COUNT类型的操作会锁定数据集,这样可以保证得到“当前”情况下的精确值. ...

  3. python学习(十三) 数据库支持

    13.1 Python数据库编程接口(API) 13.1.1 全局变量 13.1.2 异常 13.1.3 连接和游标 13.1.4 类型 13.2 SQLite和PySQlite 13.2.1 入门 ...

  4. WEB扫描器Atscan的安装和使用

    项目地址:https://github.com/AlisamTechnology/ATSCAN root@sch01ar:/sch01ar# git clone https://github.com/ ...

  5. python's sixth day for me

    ---恢复内容开始--- #  ==  比较的是数值 a = 1000 b = 1000 print(a == b) #True #  is 比较的是内存地址 >>> a = 100 ...

  6. spring-cloud配置服务器配置

    本文介绍spring-cloud配置服务器 server端配置 目录结构 依赖 java代码 properties 运行 client端配置 目录结构 依赖 java代码 properties 运行 ...

  7. 请求时控制器的返回结果view()怎么会默认调到某个页面的?

    请求时控制器的返回结果view()怎么会默认调到某个页面的? (1)请求时会拿方法行为的名字去和视图的名字对应,会默认去views视图下的与控制器名称一样的文件夹下名字与方法对应的视图文件匹配对应,然 ...

  8. leetcode375

    public class Solution { public int GetMoneyAmount(int n) { , n + ]; , n); } int DP(int[,] t, int s, ...

  9. File类的使用:遍历目录

  10. Python模块及其导入

    一.模块 1.模块的定义: 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码就相对较少, 很多编程语言都采用这种组织代码的方式.在Python中,一个.py文件 ...