陶笛伴奏曲:浅析C#中的文件操作实例

来源:百度文库 编辑:九乡新闻网 时间:2024/04/27 21:38:14
浅析C#中的文件操作
发布时间:2003.02.13 09:46     来源:赛迪网    作者:王凯明
微软的.Net框架为我们提供了基于流的I/O操作方式,这样就大大简化了开发者的工作。因为我们可以对一系列的通用对象进行操作,而不必关心该I/O操作是和本机的文件有关还是和网络中的数据有关。.Net框架主要为我们提供了一个System.IO命名空间,该命名空间基本包含了所有和I/O操作相关的类。
本文将向大家介绍一些基本的文件操作方法,包括对文件系统中的目录和文件的操作,还有就是文件的读写操作等。通过运用System.IO.DirectoryInfo类和System.IO.FileInfo类我们可以轻易的完成与目录和文件相关的操作,而通过运用System.IO.StreamReader类和System.IO.StreamWriter类我们可以方便的完成与文件的读写相关的操作。
命名空间概览
下面的表格显示了System.IO命名空间中最重要的一些类,通过运用这些类我们就能完成基本的文件操作。
表1
类名
功能和用途
BinaryReader、BinaryWriter
读写二进制数据
Directory、File、DirectoryInfo以及FileInfo
创建、删除并移动目录和文件,通过属性获取特定目录和文件的相关信息
FileStream
以随机方式访问文件
MemoryStream
访问存储在内存中的数据
StreamReader 、StreamWriter
读写文本数据信息
StringReader、StringWriter
运用字符串缓冲读写文本数据信息
运用DirectoryInfo类和FileInfo类
DirectoryInfo类和FileInfo类的基类都是FileSystemInfo类,这个类是一个抽象类,也就是说你不可以实例化该类,只能通过继承产生其子类并实例化其子类。然而你却可以运用由该类定义的各种属性,下面的表格显示了该类已经定义了的各种属性。
表2
属性
功能和用途
Attributes
返回和文件相关的属性值,运用了FileAttributes枚举类型值
CreationTime
返回文件的创建时间
Exists
检查文件是否存在于给定的目录中
Extension
返回文件的扩展名
LastAccessTime
返回文件的上次访问时间
FullName
返回文件的绝对路径
LastWriteTime
返回文件的上次写操作时间
Name
返回给定文件的文件名
Delete()
删除一个文件的方法,请务必谨慎地运用该方法
DirectoryInfo类提供了创建、删除和移动目录等方法,要运用表2中的各种属性,我们首先得创建一个DirectoryInfo类的对象,然后就可以访问其各种属性了。
DirectoryInfo dir1 = new DirectoryInfo(@"F:\Test");
Console.WriteLine("Full Name is : {0}", dir1.FullName);
Console.WriteLine("Attributes are : {0}", dir1.Attributes.ToString());
同时,我们还可以运用FileAttributes枚举类型值来获取和文件相关的各种属性,下面的表格就显示了该枚举类型中的各种值。
表3

功能和用途
Archive
返回文件的存档状态
Compressed
返回文件是否被压缩
Directory
返回文件是否是一个目录
Encrypted
返回文件是否被加密
Hidden
返回文件是否是隐藏的
Offline
表明文件数据是不可得的
ReadOnly
表明文件是只读的
System
表明文件是一个系统文件
目录下的文件操作
运用DirectoryInfo类的对象我们可以轻松的实现对目录以及和目录中的文件相关的操作,假如你要获得某个目录F:\Pictures下的所有BMP文件,那么通过下面的代码就可以实现该功能。
DirectoryInfo dir = new DirectoryInfo(@"F:\ Pictures");
FileInfo[] bmpfiles = dir.GetFiles("*.bmp);
Console.WriteLine("Total number of bmp files", bmpfiles.Length);
Foreach( FileInfo f in bmpfiles)
{
Console.WriteLine("Name is : {0}", f.Name);
Console.WriteLine("Length of the file is : {0}", f.Length);
Console.WriteLine("Creation time is : {0}", f.CreationTime);
Console.WriteLine("Attributes of the file are : {0}",
f.Attributes.ToString());
}
上面的代码中我们首先创建了一个DirectoryInfo对象,然后通过调用该对象的GetFiles方法获取目录F:\Pictures下的所有以bmp为扩展名的文件,该方法返回的值是一个FileInfo类型的数组,每个元素则代表一个文件。最后,程序还列举了每个BMP文件的相关属性。
创建子目录
运用DirectoryInfo类创建子目录是非常容易的,你只要调用其中CreateSubdirectory()方法即可,演示代码如下。
DirectoryInfo dir = new DirectoryInfo(@"F:\ Pictures");
try
{
dir.CreateSubdirectory("Sub");
dir.CreateSubdirectory(@"Sub\MySub");
}
catch(IOException e)
{
Console.WriteLine(e.Message);
}
运用FileInfo类创建、删除文件
通过FileInfo类,我们可以方便地创建出文件,并可以访问文件的属性同时还可以对文件进行打开文件、关闭文件、读写文件等基本的操作。下面的代码显示了如何创建一个文本文件并且去访问其创建时间、文件的绝对路径以及文件属性等文件信息,最后程序还给出了删除文件的方法。
FileInfo fi = new FileInfo(@"F:\Myprogram.txt");
FileStream fs = fi.Create();
Console.WriteLine("Creation Time: {0}",fi.CreationTime);
Console.WriteLine("Full Name: {0}",fi.FullName);
Console.WriteLine("FileAttributes: {0}",fi.Attributes.ToString());
Console.WriteLine("Press any key to delete the file");
Console.Read();
fstr.Close();
fi.Delete();
理解FileInfo类的Open()方法
我们在对文件进行读写操作之前必须打开文件,FileInfo类为我们提供了一个Open()方法,该方法包含了两个枚举类型值的参数,一个为FileMode枚举类型值,另一个为FileAccess枚举类型值。通过设定这两个参数值,我们可以对文件的访问模式和操作权限进行控制。下面的两个表格分别显示了FileMode枚举类型的值和FileAccess枚举类型的值。
表4

功能和用途
Append
打开文件并添加数据,运用该方法时FileAccess枚举类型值应为Write。
Create
创建一个新文件,有可能会覆盖已经存在的文件。
CreateNew
创建一个新文件,如果该文件已经存在,则抛出IOException异常。
Open
打开一个已经存在的文件。
OpenOrCreate
打开文件,如果该文件不存在,则创建之。
Truncate
截短一个已经存在的文件。
表5

功能和用途
Read
可以从一个文件中读取数据。
ReadWrite
可以从一个文件中读取数据,同时还可以向文件中写入数据。
Write
可以向文件中写入数据。
下面的代码显示了Open()方法的具体运用方法。
FileInfo f = new FileInfo("F:\MyFile.txt");
FileStream s = f.Open(FileMode.OpenorWrite, FileAccess.Read);
运用StreamReader类和StreamWriter类实现文件的读写操作
对文件的读写操作应该是最重要的文件操作,System.IO命名空间为我们提供了诸多文件读写操作类,在这里我要向大家介绍最常用也是最基本的StreamReader类和StreamWriter类。从这两个类的名称我们不难发现它们都是基于流的读写操作类。
我们可以通过File类的OpenText()方法来获取一个StreamReader对象,通过该对象我们可以实现对文本文件的读操作,方法如下:
Console.WriteLine("Reading the contents from the file");
StreamReader s = File.OpenText("MyText.txt");
string read = null;
while ((read = s.ReadLine()) != null)
{
Console.WriteLine(read);
}
s.Close();
而通过调用FileInfo类的CreateText()方法我们可以获取一个StreamWriter对象,调用StreamWriter类的WriteLine()我们就可以向文本文件中写入数据了,方法如下:
FileInfo f = new FileInfo("MyText.txt")
StreamWriter w = f.CreateText();
w.WriteLine("This is from");
w.WriteLine("Chapter 1");
w.WriteLine("Of C# Module");
w.Write(w.NewLine);
w.WriteLine("Thanks for your time");
w.Close();
总结
以上我简要地向大家介绍了C#文件操作的基本知识和方法,通过本文大家不难发现.Net框架下I/O操作的方便性。读者在学习了本文后,如果要进行一些基本的文件操作,那么对于System.IO命名空间中的诸如DirectoryInfo类、FileInfo类、FileStream类、StreamReader类以及StreamWriter类等类一定得有基本了解并在实际应用中灵活使用之。如果要对文件操作有更进一步的控制,那么不妨去研究一下System.IO命名空间中的更为具体和细节的一些类。最后,希望本文对大家能有所帮助。
(责任编辑Sunny)
C#文件及文件夹操作示例
//1.---------文件夹创建、移动、删除---------
//创建文件夹
Directory.CreateDirectory(Server.MapPath("a"));
Directory.CreateDirectory(Server.MapPath("b"));
Directory.CreateDirectory(Server.MapPath("c"));
//移动b到a
Directory.Move(Server.MapPath("b"), Server.MapPath("a\\b"));
//删除c
Directory.Delete(Server.MapPath("c"));
//2.---------文件创建、复制、移动、删除---------
//创建文件
//使用File.Create创建再复制/移动/删除时会提示:文件正由另一进程使用,因此该进程无法访问该文件
//改用 FileStream 获取 File.Create 返回的 System.IO.FileStream 再进行关闭就无此问题
FileStream fs;
fs = File.Create(Server.MapPath("a.txt"));
fs.Close();
fs = File.Create(Server.MapPath("b.txt"));
fs.Close();
fs = File.Create(Server.MapPath("c.txt"));
fs.Close();
//复制文件
File.Copy(Server.MapPath("a.txt"), Server.MapPath("a\\a.txt"));
//移动文件
File.Move(Server.MapPath("b.txt"), Server.MapPath("a\\b.txt"));
File.Move(Server.MapPath("c.txt"), Server.MapPath("a\\c.txt"));
//删除文件
File.Delete(Server.MapPath("a.txt"));
//3.---------遍历文件夹中的文件和子文件夹并显示其属性---------
if(Directory.Exists(Server.MapPath("a")))
{
//所有子文件夹
foreach(string item in Directory.GetDirectories(Server.MapPath("a")))
{
Response.Write("文件夹:" + item + "
");
DirectoryInfo directoryinfo = new DirectoryInfo(item);
Response.Write("名称:" + directoryinfo.Name + "
");
Response.Write("路径:" + directoryinfo.FullName + "
");
Response.Write("创建时间:" + directoryinfo.CreationTime + "
");
Response.Write("上次访问时间:" + directoryinfo.LastAccessTime + "
");
Response.Write("上次修改时间:" + directoryinfo.LastWriteTime + "
");
Response.Write("父文件夹:" + directoryinfo.Parent + "
");
Response.Write("所在根目录:" + directoryinfo.Root + "
");
Response.Write("
");
}
//所有子文件
foreach (string item in Directory.GetFiles(Server.MapPath("a")))
{
Response.Write("文件:" + item + "
");
FileInfo fileinfo = new FileInfo(item);
Response.Write("名称:" + fileinfo.Name + "
");
Response.Write("扩展名:" + fileinfo.Extension +"
");
Response.Write("路径:" + fileinfo.FullName +"
");
Response.Write("大小:" + fileinfo.Length +"
");
Response.Write("创建时间:" + fileinfo.CreationTime +"
");
Response.Write("上次访问时间:" + fileinfo.LastAccessTime +"
");
Response.Write("上次修改时间:" + fileinfo.LastWriteTime +"
");
Response.Write("所在文件夹:" + fileinfo.DirectoryName +"
");
Response.Write("文件属性:" + fileinfo.Attributes +"
");
Response.Write("
");
}
}
//4.---------文件读写---------
if (File.Exists(Server.MapPath("a\\a.txt")))
{
StreamWriter streamwrite = new StreamWriter(Server.MapPath("a\\a.txt"));
streamwrite.WriteLine("木子屋");
streamwrite.WriteLine("http://www.mzwu.com/");
streamwrite.Write("2008-04-13");
streamwrite.Close();
StreamReader streamreader = new StreamReader(Server.MapPath("a\\a.txt"));
Response.Write(streamreader.ReadLine());
Response.Write(streamreader.ReadToEnd());
streamreader.Close();
}
下篇
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ShowPic.Visible = false;//初始化不显示
ShowText.Visible = false;//初始化不显示
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Directory.Exists(Server.MapPath("~/upimg/hufu")) == false)//如果不存在就创建file文件夹
{
Directory.CreateDirectory(Server.MapPath("~/upimg/hufu"));
}
//Directory.Delete(Server.MapPath("~/upimg/hufu"), true);//删除文件夹以及文件夹中的子目录,文件
//判断文件的存在
if (File.Exists(Server.MapPath("~/upimg/Data.html")))
{
Response.Write("Yes");
//存在文件
}
else
{
Response.Write("No");
//不存在文件
File.Create(MapPath("~/upimg/Data.html"));//创建该文件
}
string name = GetFiles.FileName;//获取已上传文件的名字
string size = GetFiles.PostedFile.ContentLength.ToString();//获取已上传文件的大小
string type = GetFiles.PostedFile.ContentType;//获取已上传文件的MIME
string postfix = name.Substring(name.LastIndexOf(".") + 1);//获取已上传文件的后缀
string ipath = Server.MapPath("upimg") +"\\"+ name;//获取文件的实际路径
string fpath = Server.MapPath("upfile") + "\\" + name;
string dpath = "upimg\\" + name;//判断写入数据库的虚拟路径
ShowPic.Visible = true;//激活
ShowText.Visible = true;//激活
//判断文件格式
if (name == "") {
Response.Write("");
}
else{
if (postfix == "jpg" || postfix == "gif" || postfix == "bmp" || postfix == "png")
{
GetFiles.SaveAs(ipath);
ShowPic.ImageUrl = dpath;
ShowText.Text = "你上传的图片名称是:" + name + "
" + "文件大小:" + size + "KB" + "
" + "文件类型:" + type + "
" + "存放的实际路径为:" + ipath;
}
else
{
ShowPic.Visible = false;//隐藏图片
GetFiles.SaveAs(fpath);//由于不是图片文件,因此转存在upfile这个文件夹
ShowText.Text = "你上传的文件名称是:" + name + "
" + "文件大小:" + size + "KB" + "
" + "文件类型:" + type + "
" + "存放的实际路径为:" + fpath;
}
}
}
}