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接口的性能测试

    这周尝试了一把性能测试,之前都是测试网站的性能测试,java接口的性能测试还是头一次,学到了很多,特此分享一下. 主要用到了两个性能测试工具,一个是jmeter,一个是LoadRunner. 使用jm ...

  2. Vue.js:组件

    ylbtech-Vue.js:组件 1.返回顶部 1. Vue.js 组件 组件(Component)是 Vue.js 最强大的功能之一. 组件可以扩展 HTML 元素,封装可重用的代码. 组件系统让 ...

  3. PHP实现四种基本排序算法 得多消化消化

    1.冒泡排序 // 冒泡排序 思路分析:在要排序的一组数中,对当前还未排好的序列,从前往后对相邻的两个数依次进行比较和调整,让较大的数往下沉,较小的往上冒.即,每当两相邻的数比较后发现它们的排序与排序 ...

  4. Python多线程-事件

    线程事件用于线程控制线程,实现多个进程间的交互,线程事件的初始值为False set:将线程事件的值设为True clear:将线程事件的值设为False # -*- coding:utf-8 -*- ...

  5. java成神之——集合框架之Maps,Hashtable

    集合 Maps HashMap 创建和初始化map 遍历方式 LinkedHashMap WeakHashMap TreeMap 线程锁 Hashtable 结语 集合 Maps HashMap Ma ...

  6. DIV+CSS+JS实现图片<ul><li></li></ul>无缝滚动代码

    (含上下左右滚动代码) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:/ ...

  7. 配置key认证登陆Ubuntu (上)

    每一个看似轻松的结果背后都有不为人知的辛酸.又是一件小事,结果折腾了一天. 上接配置好SSH 和Samba后,开始了Python编程实践.由于实在不大会用Vim, 所以最后的编程环境实际上在Windo ...

  8. vue中使用markdown富文本,并在html页面中展示

    想给自己的后台增加一个markdown编辑器,下面记录下引用的步骤 引入组件mavon-editor 官网地址:https://github.com/hinesboy/mavonEditor // 插 ...

  9. wpa_supplicant移植与使用(转)

    下载wpa_supplicant最新版和openssl(编译wpa_supplicant需要openssl的库) 我这里使用的是wpa_supplicant-0.7.3.tar.gz和openssl- ...

  10. AngularJS学习(二)——Angular应用的解析

    本节描述AngularJS应用程序的三个组成部分,并解释它们如何映射到模型-视图-控制器设计模式 模板(Template) 模板是您用HTML和CSS编写的文件,展现应用的视图.您可给HTML添加新的 ...