C# File类常用方法
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 方法 —— 将指定的字符串追加到文件中,如果文件还不存在则创建该文件。
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类常用方法的更多相关文章
- java File类常用方法
file类常用方法 delete()删除此抽象路径名表示的文件和目录. equals()测试此抽象路径名与给定对象是否相等. exists()测试此抽象路径名表示的文件或目录是否存在. getName ...
- File类常用方法和枚举
新建一个file对象: File f = new File("F:\\01.JAVA基础300集\\05_常用类\\122.File类的使用.mp4"); (文件路径也可以用&qu ...
- File类常用方法
File类是IO中常用的类 先介绍几个常用的方法: public boolean canRead(),public boolean canWrite() 测试当前文件是否可读可写,若是则返回true ...
- Java File类常用方法及实例
创建:createNewFile()在指定位置创建一个空文件,成功就返回true,如果已存在就不创建,然后返回false. createTempFile(String prefix, String s ...
- 62. File类常用方法
为了怕混淆,先说明一些下面要出现的名词意思:例如:D:\\新建文件夹 (2)\\a.txt 和 D:\\新建文件夹 (2)\\aaaa D:\\新建文件夹 (2) 父路径 a.txt ...
- I/O流——File类及使用
I/O框架介绍 I/O是计算机输入/输出的接口.Java的核心库java.io提供了全方面的I/O接口,包括:文件系统的操作,文件读写,标准设备的输出等. File类及使用 ① 一个File类的对 ...
- File类
存储在变量,数组和对象中的数据是暂时的,当程序终止时他们就会丢失.为了能够永久的保存程序中创建的数据,需要将他们存储到硬盘或光盘的文件中.这些文件可以移动,传送,亦可以被其他程序使用.由于数据存储在文 ...
- Java文件File类学习总结
java.io.File类 代表文件和目录,在开发中,读取文件.生成文件.删除文件.修改文件的属性都会用到该类. 常见构造方法: public File(String pathName){} 以pat ...
- Java常用类之File类
File 类: 1. java.io.File 类代表系统文件名(路径名.文件名); 2. File 类常见的构造方法: 2.1. File(String pathname):通过将给定路径名字符串转 ...
随机推荐
- java代码用户界面网格布局GridLayout.划分为格子区域
总结:网格布局.很简单,首先要new一个 this.setlayout(new GriedLayout(3,5));里面是行数和列数 package clientFrame; //网格布局练习 i ...
- 几种经典的hash算法
计算理论中,没有Hash函数的说法,只有单向函数的说法.所谓的单向函数,是一个复杂的定义,大家可以去看计算理论或者密码学方面的数据.用“人 类”的语言描述单向函数就是:如果某个函数在给定输入的时候,很 ...
- 1139 First Contact
题意:给出n个人,m对朋友关系,其中带负号的表示女孩.然后给出k对查询a,b,要求找出所有a的同性别好友c,以及b的同性别好友d,且c和d又是好友关系.输出所有满足条件的c和d,按c的升序输出,若c编 ...
- Oracle 常见hint
Hints 应该慎用,收集相关表的统计信息,根据执行计划,来改变查询方式 只能在SELECT, UPDATE, INSERT, MERGE, or DELETE 关键字后面,只有insert可以用2个 ...
- mybatis foreach标签的解释 与常用之处
情景:查询数据库中文章的相关文章 文章为一个表 字段tags为相关文章字符串中间用','逗号进行啦分割 查询完一个文章后可以把tags字段构造为一个List<String> 然后利用这 ...
- 编译openwrt失败 “Please install theopenssl library”
make menuconfig出现了错误 Build dependency: Please install theopenssl library(with development headers) P ...
- Py修行路 python基础 (九)作用域 函数嵌套 闭包
名称空间与作用域 变量,函数 分成三种 #内置名称空间 内置函数, 系统函数内部自定义的. python查看内置函数,命令: import builtins dir(builtins) #全局名称空 ...
- 讲解一下this (作用域)
this的指向:普通函数内的this指向全局变量 构造函数内部this指向新创建出来的对象 对象方法内的this指向的是调用该方法的对象 call,apply,bind可以改变this的指向
- C#通用模块专题
开源 程序设计 常用组件 加载图片,播放音乐.视频,摄像头拍照 文件读写(txt.xml.自定义文件格式(后缀名)) 串口通信 稳定的串口读写:http://blog.csdn.net/kolvin2 ...
- 取当前时间,格式为,yyyy-mm-dd hh:mm:ss
function CurentTime() { var now = new Date(); var year = now.getFullYear(); //年 var month = now.getM ...