操作文件 (File和FileInfo类)
2010-12-11 10:49
483 查看
使用File和FileInfo类操作文件
.NET Framework类库包含用于处理文件的两个类似的类:FileInfo和File.File类为创建、删除和操作文件提供静态方法,而FileInfo类为文件操作提供实例方法。类似与Directory类,File类只提供静态方法,而没有包含任何特性。
view plaincopy to clipboardprint?
using System;
using System.IO;
namespace ConsoleApplicationFile
{
class Program
{
static void Main(string[] args)
{
string filePath = @"D:/temp/textfile.txt";
string fileCopyPath = @"D:/temp/textfile_copy.txt";
string newFileName = @"D:/temp/textfile_newcopy.txt";
try
{
//---if file already existed---
if (File.Exists(filePath))
{
//---delete the file---
File.Delete(filePath);
}
//---create the file again
FileStream fs = File.Create(filePath);
fs.Close();
//---make a copy of the file---
File.Copy(filePath, fileCopyPath);
//---rename the file---
File.Move(fileCopyPath, newFileName);
//---display the creation time---
Console.WriteLine(File.GetCreationTime(newFileName));
//---make the file read-only and hidden---
File.SetAttributes(newFileName, FileAttributes.ReadOnly);
File.SetAttributes(newFileName, FileAttributes.Hidden);
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
File类包含用于将内容写入文件的4种方法:
WriteAllText():创建文本,将字符串写入该文件,关闭文件
AppendAllText():将字符串附加到已有的文件
WriteAllLines():创建文件,将字符串数组写入该文件,关闭文件
WriteAllBytes():创建文件,将字节数组写入该文件,关闭文件
下面的代码显示了如何使用各种方法将一些内容写入文件:
view plaincopy to clipboardprint?
using System;
using System.IO;
using System.Text;
namespace ConsoleApplicationFile
{
class Program
{
static void Main(string[] args)
{
string filePath = @"D:/temp/textfile.txt";
string strTextToWrite = "This is a string";
string[] strLinesToWrite = new string[] { "Line1","Line2"};
byte[] bytesToWrite = ASCIIEncoding.ASCII.GetBytes("This is a string");
try
{
File.WriteAllText(filePath, strTextToWrite);
File.AppendAllText(filePath, strTextToWrite);
File.WriteAllLines(filePath, strLinesToWrite);
File.WriteAllBytes(filePath, bytesToWrite);
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
File类也包含用于从文件读取内容的3种方法:
ReadAllText():打开文件,读取该文件中的所有文本并放入字符串中,关闭文件
ReadAllLines():打开文件,读取该文件中的所有文本并放入字符串数组中,关闭文件
ReadAllBytes():打开文件,读取该文件中的所有文本并放入字节数组中,关闭文件
相关文章推荐
- Xml文件操作和文件操作(FileInfo类)
- Xml文件操作和文件操作(FileInfo类)
- vb.net 教程 4-3 文件操作 FileInfo 1
- vb.net 教程 4-3 文件操作 FileInfo 2
- C#的FileInfo类实现文件操作实例
- 使用VB.NET的FileInfo和DirectoryInfo类进行文件操作
- C#文件操作-File类和FileInfo类有什么区别?
- 第四章:文件操作——文件管理(File/FileInfo)
- C#中FileInfo类操作文件实例
- 使用File和FileInfo类操作文件
- File文件操作和其他流对象
- 文件操作总结 (Path,Directory,File)
- C#中IO类FileInfo和Directory操作实例
- Windows资源文件里VarFileInfo的Translation(EXE的语言描述信息)
- Python文件\文件夹操作—OS, File, Shutil
- File各种类操作文件、文件夹
- File文件的 基本操作
- 利用FileSystemWatcher监控对文件的操作
- 转:文件操作之File类使用
- wxWidgets文件操作(三)wxFileDialog与wxTextCtrl