(文本)文件操作

 其实,建立一个文本文件、写一个文本文件、读取一个文本文件是一件非常容易的事情,但是当你查MSDN的时候,你会发现,有很多的方法,比如,在你第一次做“写文件”操作的时候就可以直接建立一个新的文件等等……

这么多的方法,和构造函数,令我眼花缭乱。
下面将这三个操作独立出来,分别用代码表示:

0、首先写个文件路径,为下面的操作做准备。

  private string fileName = @"c:\test.txt";


1、建立文件:

  FileStream fs = File.Create(fileName);
  fs.Close();
  
// You have created a file: c:\test.txt.
  
// And if this file existent, it will be covered by new.


2、写操作:

  // Remarks: the method and StreamWriter(String, Boolean) equivalent.
  // If this file does not exist, then creates this file.
  StreamWriter sw = File.AppendText(fileName);
  sw.WriteLine(
"AAAAA");
  sw.Close();
  
// Check c:\test.txt, it should be writed.
using (FileStream fs = new FileStream(LicenseFile, FileMode.Open, FileAccess.Write))
{
        using(StreamWriter sw = new StreamWriter(fs))
        {
                sw.WriteLine("");
                //sw.Flush();
        }
}


3、读操作:

  // Remarks: the file represented by the argument must exist,
  // and the user must have permission to open it,
  // otherwise OpenText(fileName) throws an exception.
StreamReader sr = File.OpenText(fileName);
  
string str;
  
while((str = sr.ReadLine()) != null)
    
{
        
// Get a line text, and do some else operation.
    }

  sr.Close();
using (FileStream fs = new FileStream(LicenseFile, FileMode.Open, FileAccess.Read))
{
    using (StreamReader sr = new StreamReader(fs))
    {
        if (string.IsNullOrWhiteSpace(str = sr.ReadLine()))
        {
            // License file is empty.
            return false;
        }
    }
}


例:

        private void writeLog(string logString)
        {
            
string file = @"D:\log.txt";
            System.IO.FileStream fs 
= System.IO.File.Create(file);
            fs.Close();

            
using(System.IO.StreamWriter sw = System.IO.File.AppendText(file))
            {
                sw.WriteLine(logString);
                sw.Close();
            }
        }
 1//C#追加文件 
 2StreamWriter sw = File.AppendText(Server.MapPath(".")+"\\myText.txt"); 
 3sw.WriteLine("追逐理想"); 
 4sw.WriteLine("kzlll"); 
 5sw.WriteLine(".NET笔记"); 
 6sw.Flush(); 
 7sw.Close(); 
 8
 9//C#拷贝文件 
10string OrignFile,NewFile; 
11OrignFile = Server.MapPath(".")+"\\myText.txt"
12NewFile = Server.MapPath(".")+"\\myTextCopy.txt"
13File.Copy(OrignFile,NewFile,true); 
14
15//C#删除文件 
16string delFile = Server.MapPath(".")+"\\myTextCopy.txt"
17File.Delete(delFile); 
18
19//C#移动文件 
20string OrignFile,NewFile; 
21OrignFile = Server.MapPath(".")+"\\myText.txt"
22NewFile = Server.MapPath(".")+"\\myTextCopy.txt"
23File.Move(OrignFile,NewFile); 
24
25//C#创建目录 
26// 创建目录c:\sixAge 
27DirectoryInfo d=Directory.CreateDirectory("c:\\sixAge"); 
28// d1指向c:\sixAge\sixAge1 
29DirectoryInfo d1=d.CreateSubdirectory("sixAge1"); 
30// d2指向c:\sixAge\sixAge1\sixAge1_1 
31DirectoryInfo d2=d1.CreateSubdirectory("sixAge1_1"); 
32// 将当前目录设为c:\sixAge 
33Directory.SetCurrentDirectory("c:\\sixAge"); 
34// 创建目录c:\sixAge\sixAge2 
35Directory.CreateDirectory("sixAge2"); 
36// 创建目录c:\sixAge\sixAge2\sixAge2_1 
37Directory.CreateDirectory("sixAge2\\sixAge2_1"); 
38
39//递归删除文件夹及文件 
40<%@ Page Language=C#%> 
41<%@ Import namespace="System.IO"%> 
42<Script runat=server> 
43public void DeleteFolder(string dir) 
44
45    if (Directory.Exists(dir)) //如果存在这个文件夹删除之 
46    
47        foreach(string d in Directory.GetFileSystemEntries(dir)) 
48        
49            if(File.Exists(d)) 
50                File.Delete(d); //直接删除其中的文件 
51            else 
52                DeleteFolder(d); //递归删除子文件夹 
53        }
 
54        Directory.Delete(dir); //删除已空文件夹 
55        Response.Write(dir+" 文件夹删除成功"); 
56    }
 
57    else 
58        Response.Write(dir+" 该文件夹不存在"); //如果文件夹不存在则提示 
59}
 
60
61protected void Page_Load (Object sender ,EventArgs e) 
62
63    string Dir="D:\\gbook\\11"
64    DeleteFolder(Dir); //调用函数删除文件夹 
65}



  // ======================================================
  // 实现一个静态方法将指定文件夹下面的所有内容copy到目标文件夹下面
  // 如果目标文件夹为只读属性就会报错。
  // April 18April2005 In STU
  // ======================================================

 1public static void CopyDir(string srcPath,string aimPath)
 2{
 3    try
 4    {
 5        // 检查目标目录是否以目录分割字符结束如果不是则添加之
 6        if(aimPath[aimPath.Length-1!= Path.DirectorySeparatorChar) 
 7            aimPath += Path.DirectorySeparatorChar;
 8        // 判断目标目录是否存在如果不存在则新建之
 9        if(!Directory.Exists(aimPath)) 
10            Directory.CreateDirectory(aimPath);
11        // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
12        // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
13        // string[] fileList = Directory.GetFiles(srcPath);
14        string[] fileList = Directory.GetFileSystemEntries(srcPath);
15        // 遍历所有的文件和目录
16        foreach(string file in fileList)
17        {
18            // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
19            if(Directory.Exists(file))
20                CopyDir(file,aimPath+Path.GetFileName(file));
21            // 否则直接Copy文件
22            else
23                File.Copy(file,aimPath+Path.GetFileName(file),true);
24        }

25    }

26    catch (Exception e)
27    {
28        MessageBox.Show (e.ToString());
29    }

30}

  // ======================================================
  // 实现一个静态方法将指定文件夹下面的所有内容Detele
  // 测试的时候要小心操作,删除之后无法恢复。
  // April 18April2005 In STU
  // ======================================================

 1public static void DeleteDir(string aimPath)
 2{
 3    try
 4    {
 5        // 检查目标目录是否以目录分割字符结束如果不是则添加之
 6        if(aimPath[aimPath.Length-1!= Path.DirectorySeparatorChar) 
 7            aimPath += Path.DirectorySeparatorChar;
 8        // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
 9        // 如果你指向Delete目标文件下面的文件而不包含目录请使用下面的方法
10        // string[] fileList = Directory.GetFiles(aimPath);
11        string[] fileList = Directory.GetFileSystemEntries(aimPath);
12        // 遍历所有的文件和目录
13        foreach(string file in fileList)
14        {
15            // 先当作目录处理如果存在这个目录就递归Delete该目录下面的文件
16            if(Directory.Exists(file))
17            {
18                DeleteDir(aimPath+Path.GetFileName(file));
19            }

20            // 否则直接Delete文件
21            else
22            {
23                File.Delete (aimPath+Path.GetFileName(file));
24            }

25        }

26        //删除文件夹
27        System.IO .Directory .Delete (aimPath,true);
28    }

29    catch (Exception e)
30    {
31        MessageBox.Show (e.ToString());
32    }

33}
原文地址:https://www.cnblogs.com/publicbill/p/295612.html