c#文件操作(二)

简介:

一.读取文本文件

 1 ExpandedBlockStart.gif /// <summary>
 2InBlock.gif/// 读取文本文件
 3ExpandedBlockEnd.gif/// </summary>

 4 None.gif private   void  ReadFromTxtFile()
 5 ExpandedBlockStart.gif {
 6InBlock.gif    if(filePath.PostedFile.FileName != "")
 7ExpandedSubBlockStart.gif    {
 8InBlock.gif        txtFilePath =filePath.PostedFile.FileName;
 9InBlock.gif        fileExtName = txtFilePath.Substring(txtFilePath.LastIndexOf(".")+1,3);
10InBlock.gif
11InBlock.gif        if(fileExtName !="txt" && fileExtName != "TXT")
12ExpandedSubBlockStart.gif        {
13InBlock.gif            Response.Write("请选择文本文件");
14ExpandedSubBlockEnd.gif        }

15InBlock.gif        else
16ExpandedSubBlockStart.gif        {
17InBlock.gif            StreamReader fileStream = new StreamReader(txtFilePath,Encoding.Default);
18InBlock.gif            txtContent.Text = fileStream.ReadToEnd();
19InBlock.gif            fileStream.Close();
20ExpandedSubBlockEnd.gif        }

21ExpandedSubBlockEnd.gif    }

22ExpandedBlockEnd.gif}

二.获取文件列表

  1 ExpandedBlockStart.gif /// <summary>
  2InBlock.gif/// 获取文件列表
  3ExpandedBlockEnd.gif/// </summary>

  4 None.gif private   void  GetFileList()
  5 ExpandedBlockStart.gif {
  6InBlock.gif    string strCurDir,FileName,FileExt;
  7InBlock.gif    
  8ExpandedSubBlockStart.gif    ///文件大小
  9InBlock.gif    long FileSize;
 10InBlock.gif    
 11ExpandedSubBlockStart.gif    ///最后修改时间;
 12InBlock.gif    DateTime FileModify;
 13InBlock.gif
 14ExpandedSubBlockStart.gif    ///初始化
 15InBlock.gif    if(!IsPostBack)
 16ExpandedSubBlockStart.gif    {
 17ExpandedSubBlockStart.gif        ///初始化时,默认为当前页面所在的目录
 18InBlock.gif        strCurDir = Server.MapPath(".");
 19InBlock.gif        lblCurDir.Text = strCurDir;
 20InBlock.gif        txtCurDir.Text = strCurDir;
 21ExpandedSubBlockEnd.gif    }

 22InBlock.gif    else
 23ExpandedSubBlockStart.gif    {
 24InBlock.gif        strCurDir = txtCurDir.Text;
 25InBlock.gif        txtCurDir.Text = strCurDir;
 26InBlock.gif        lblCurDir.Text = strCurDir;
 27ExpandedSubBlockEnd.gif    }

 28InBlock.gif    FileInfo fi;
 29InBlock.gif    DirectoryInfo dir;
 30InBlock.gif    TableCell td;
 31InBlock.gif    TableRow tr;
 32InBlock.gif    tr = new TableRow();
 33InBlock.gif    
 34ExpandedSubBlockStart.gif    ///动态添加单元格内容
 35InBlock.gif    td = new TableCell();
 36InBlock.gif    td.Controls.Add(new LiteralControl("文件名"));
 37InBlock.gif    tr.Cells.Add(td);
 38InBlock.gif    td = new TableCell();
 39InBlock.gif    td.Controls.Add(new LiteralControl("文件类型"));
 40InBlock.gif    tr.Cells.Add(td);
 41InBlock.gif    td = new TableCell();
 42InBlock.gif    td.Controls.Add(new LiteralControl("文件大小"));
 43InBlock.gif    tr.Cells.Add(td);
 44InBlock.gif    td = new TableCell();
 45InBlock.gif    td.Controls.Add(new LiteralControl("最后修改时间"));
 46InBlock.gif    tr.Cells.Add(td);
 47InBlock.gif
 48InBlock.gif    tableDirInfo.Rows.Add(tr);
 49InBlock.gif    
 50ExpandedSubBlockStart.gif    ///针对当前目录建立目录引用对象
 51InBlock.gif    DirectoryInfo dirInfo = new DirectoryInfo(txtCurDir.Text);
 52InBlock.gif    
 53ExpandedSubBlockStart.gif    ///循环判断当前目录下的文件和目录
 54InBlock.gif    foreach(FileSystemInfo fsi in dirInfo.GetFileSystemInfos())
 55ExpandedSubBlockStart.gif    {
 56InBlock.gif        FileName = "";
 57InBlock.gif        FileExt = "";
 58InBlock.gif        FileSize = 0;
 59InBlock.gif        
 60ExpandedSubBlockStart.gif        ///如果是文件
 61InBlock.gif        if(fsi is FileInfo)
 62ExpandedSubBlockStart.gif        {
 63InBlock.gif            fi = (FileInfo)fsi;
 64InBlock.gif            
 65ExpandedSubBlockStart.gif            ///取得文件名
 66InBlock.gif            FileName = fi.Name;
 67InBlock.gif            
 68ExpandedSubBlockStart.gif            ///取得文件的扩展名
 69InBlock.gif            FileExt = fi.Extension;
 70InBlock.gif            
 71ExpandedSubBlockStart.gif            ///取得文件的大小
 72InBlock.gif            FileSize = fi.Length;
 73InBlock.gif            
 74ExpandedSubBlockStart.gif            ///取得文件的最后修改时间
 75InBlock.gif            FileModify = fi.LastWriteTime;
 76ExpandedSubBlockEnd.gif        }

 77InBlock.gif
 78ExpandedSubBlockStart.gif        ///否则是目录
 79InBlock.gif        else
 80ExpandedSubBlockStart.gif        {
 81InBlock.gif            dir = (DirectoryInfo)fsi;
 82InBlock.gif            
 83ExpandedSubBlockStart.gif            ///取得目录名
 84InBlock.gif            FileName = dir.Name;
 85InBlock.gif            
 86ExpandedSubBlockStart.gif            ///取得目录的最后修改时间
 87InBlock.gif            FileModify = dir.LastWriteTime;
 88InBlock.gif            
 89ExpandedSubBlockStart.gif            ///设置文件的扩展名为"文件夹"
 90InBlock.gif            FileExt = "文件夹";
 91ExpandedSubBlockEnd.gif        }

 92InBlock.gif        
 93ExpandedSubBlockStart.gif        ///动态添加表格内容
 94InBlock.gif        tr = new TableRow();
 95InBlock.gif        td = new TableCell();
 96InBlock.gif        td.Controls.Add(new LiteralControl(FileName));
 97InBlock.gif        tr.Cells.Add(td);
 98InBlock.gif        td = new TableCell();
 99InBlock.gif        td.Controls.Add(new LiteralControl(FileExt));
100InBlock.gif        tr.Cells.Add(td);
101InBlock.gif        td = new TableCell();
102InBlock.gif        td.Controls.Add(new LiteralControl(FileSize.ToString()+"字节"));
103InBlock.gif        tr.Cells.Add(td);
104InBlock.gif        td = new TableCell();
105InBlock.gif        td.Controls.Add(new LiteralControl(FileModify.ToString("yyyy-mm-dd hh:mm:ss")));
106InBlock.gif        tr.Cells.Add(td);
107InBlock.gif        tableDirInfo.Rows.Add(tr);
108ExpandedSubBlockEnd.gif    }

109ExpandedBlockEnd.gif}

三.读取日志文件

 1 ExpandedBlockStart.gif /// <summary>
 2InBlock.gif/// 读取日志文件
 3ExpandedBlockEnd.gif/// </summary>

 4 None.gif private   void  ReadLogFile()
 5 ExpandedBlockStart.gif {
 6ExpandedSubBlockStart.gif    ///从指定的目录以打开或者创建的形式读取日志文件
 7InBlock.gif    FileStream fs  = new FileStream(Server.MapPath("upedFile")+"\\logfile.txt", FileMode.OpenOrCreate, FileAccess.Read);
 8InBlock.gif
 9ExpandedSubBlockStart.gif    ///定义输出字符串
10InBlock.gif    StringBuilder output = new StringBuilder();
11InBlock.gif    
12ExpandedSubBlockStart.gif    ///初始化该字符串的长度为0
13InBlock.gif    output.Length = 0;
14InBlock.gif    
15ExpandedSubBlockStart.gif    ///为上面创建的文件流创建读取数据流
16InBlock.gif    StreamReader read = new StreamReader(fs);
17InBlock.gif    
18ExpandedSubBlockStart.gif    ///设置当前流的起始位置为文件流的起始点
19InBlock.gif    read.BaseStream.Seek(0, SeekOrigin.Begin);
20InBlock.gif    
21ExpandedSubBlockStart.gif    ///读取文件
22InBlock.gif    while (read.Peek() > -1
23ExpandedSubBlockStart.gif    {
24ExpandedSubBlockStart.gif        ///取文件的一行内容并换行
25InBlock.gif        output.Append(read.ReadLine() + "\n");
26ExpandedSubBlockEnd.gif    }

27InBlock.gif    
28ExpandedSubBlockStart.gif    ///关闭释放读数据流
29InBlock.gif    read.Close();
30InBlock.gif    
31ExpandedSubBlockStart.gif    ///返回读到的日志文件内容
32InBlock.gif    return output.ToString();
33ExpandedBlockEnd.gif}

四.写入日志文件

 1 ExpandedBlockStart.gif /// <summary>
 2InBlock.gif/// 写入日志文件
 3InBlock.gif/// </summary>
 4ExpandedBlockEnd.gif/// <param name="input"></param>

 5 None.gif private   void  WriteLogFile( string  input)
 6 ExpandedBlockStart.gif {    
 7ExpandedSubBlockStart.gif    ///指定日志文件的目录
 8InBlock.gif    string fname = Server.MapPath("upedFile"+ "\\logfile.txt";
 9ExpandedSubBlockStart.gif    ///定义文件信息对象
10InBlock.gif    FileInfo finfo = new FileInfo(fname);
11InBlock.gif
12ExpandedSubBlockStart.gif    ///判断文件是否存在以及是否大于2K
13InBlock.gif    if ( finfo.Exists && finfo.Length > 2048 )
14ExpandedSubBlockStart.gif    {
15ExpandedSubBlockStart.gif        ///删除该文件
16InBlock.gif        finfo.Delete();
17ExpandedSubBlockEnd.gif    }

18ExpandedSubBlockStart.gif    ///创建只写文件流
19InBlock.gif    using(FileStream fs = finfo.OpenWrite())
20ExpandedSubBlockStart.gif    {
21ExpandedSubBlockStart.gif        ///根据上面创建的文件流创建写数据流
22InBlock.gif        StreamWriter w = new StreamWriter(fs);
23InBlock.gif        
24ExpandedSubBlockStart.gif        ///设置写数据流的起始位置为文件流的末尾
25InBlock.gif        w.BaseStream.Seek(0, SeekOrigin.End);
26InBlock.gif        
27ExpandedSubBlockStart.gif        ///写入“Log Entry : ”
28InBlock.gif        w.Write("\nLog Entry : ");
29InBlock.gif        
30ExpandedSubBlockStart.gif        ///写入当前系统时间并换行
31InBlock.gif        w.Write("{0} {1} \r\n", DateTime.Now.ToLongTimeString(),
32InBlock.gif            DateTime.Now.ToLongDateString());
33InBlock.gif        
34ExpandedSubBlockStart.gif        ///写入日志内容并换行
35InBlock.gif        w.Write(input + "\n");
36InBlock.gif        
37ExpandedSubBlockStart.gif        ///写入------------------------------------“并换行
38InBlock.gif        w.Write("------------------------------------\n");
39InBlock.gif        
40ExpandedSubBlockStart.gif        ///清空缓冲区内容,并把缓冲区内容写入基础流
41InBlock.gif        w.Flush();
42InBlock.gif        
43ExpandedSubBlockStart.gif        ///关闭写数据流
44InBlock.gif        w.Close();
45ExpandedSubBlockEnd.gif    }

46ExpandedBlockEnd.gif}

五.创建HTML文件

 1 ExpandedBlockStart.gif /// <summary>
 2InBlock.gif/// 创建HTML文件
 3ExpandedBlockEnd.gif/// </summary>

 4 None.gif private   void  CreateHtmlFile()
 5 ExpandedBlockStart.gif {    
 6ExpandedSubBlockStart.gif    ///定义和html标记数目一致的数组
 7InBlock.gif    string[] newContent = new string[5];
 8InBlock.gif    StringBuilder strhtml = new StringBuilder();
 9InBlock.gif    try 
10ExpandedSubBlockStart.gif    {
11ExpandedSubBlockStart.gif        ///创建StreamReader对象
12InBlock.gif        using (StreamReader sr = new StreamReader(Server.MapPath("createHTML"+ "\\template.html")) 
13ExpandedSubBlockStart.gif        {
14InBlock.gif            String oneline;
15InBlock.gif            
16ExpandedSubBlockStart.gif            ///读取指定的HTML文件模板
17InBlock.gif            while ((oneline = sr.ReadLine()) != null
18ExpandedSubBlockStart.gif            {
19InBlock.gif                strhtml.Append(oneline);
20ExpandedSubBlockEnd.gif            }

21InBlock.gif            sr.Close();
22ExpandedSubBlockEnd.gif        }

23ExpandedSubBlockEnd.gif    }

24InBlock.gif    catch(Exception err)
25ExpandedSubBlockStart.gif    {
26ExpandedSubBlockStart.gif        ///输出异常信息
27InBlock.gif        Response.Write(err.ToString());
28ExpandedSubBlockEnd.gif    }

29ExpandedSubBlockStart.gif    ///为标记数组赋值
30InBlock.gif    newContent[0= txtTitle.Text;//标题
31InBlock.gif    newContent[1= "BackColor='#cccfff'";//背景色
32InBlock.gif    newContent[2= "#ff0000";//字体颜色
33InBlock.gif    newContent[3= "100px";//字体大小
34InBlock.gif    newContent[4= txtContent.Text;//主要内容
35InBlock.gif
36ExpandedSubBlockStart.gif    ///根据上面新的内容生成html文件
37InBlock.gif    try
38ExpandedSubBlockStart.gif    {
39ExpandedSubBlockStart.gif        ///指定要生成的HTML文件
40InBlock.gif        string fname = Server.MapPath("createHTML"+"\\" + DateTime.Now.ToString("yyyymmddhhmmss"+ ".html";
41InBlock.gif        
42ExpandedSubBlockStart.gif        ///替换html模版文件里的标记为新的内容
43InBlock.gif        for(int i=0;i < 5;i++)
44ExpandedSubBlockStart.gif        {
45InBlock.gif            strhtml.Replace("$htmlkey["+i+"]",newContent[i]);
46ExpandedSubBlockEnd.gif        }

47ExpandedSubBlockStart.gif        ///创建文件信息对象
48InBlock.gif        FileInfo finfo = new FileInfo(fname);
49InBlock.gif        
50ExpandedSubBlockStart.gif        ///以打开或者写入的形式创建文件流
51InBlock.gif        using(FileStream fs = finfo.OpenWrite())
52ExpandedSubBlockStart.gif        {
53ExpandedSubBlockStart.gif            ///根据上面创建的文件流创建写数据流
54InBlock.gif            StreamWriter sw = new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
55InBlock.gif            
56ExpandedSubBlockStart.gif            ///把新的内容写到创建的HTML页面中
57InBlock.gif            sw.WriteLine(strhtml);
58InBlock.gif            sw.Flush();
59InBlock.gif            sw.Close();
60ExpandedSubBlockEnd.gif        }

61InBlock.gif        
62ExpandedSubBlockStart.gif        ///设置超级链接的属性
63InBlock.gif        hyCreateFile.Text = DateTime.Now.ToString("yyyymmddhhmmss")+".html";
64InBlock.gif        hyCreateFile.NavigateUrl = "createHTML/"+DateTime.Now.ToString("yyyymmddhhmmss")+".html";
65ExpandedSubBlockEnd.gif    }

66InBlock.gif    catch(Exception err)
67ExpandedSubBlockStart.gif    
68InBlock.gif        Response.Write (err.ToString());
69ExpandedSubBlockEnd.gif    }

70ExpandedBlockEnd.gif}



本文转自高海东博客园博客,原文链接:http://www.cnblogs.com/ghd258/archive/2005/12/01/288691.html,如需转载请自行联系原作者
相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
相关文章
|
2月前
|
C#
C# 文件操作(全部) 追加、拷贝、删除、移动文件、创建目录
C# 文件操作(全部) 追加、拷贝、删除、移动文件、创建目录
25 0
|
8月前
|
C#
使用C#进行文件操作
在许多应用程序中,文件操作是常见的任务之一。无论是读取文件内容、写入数据,还是创建、移动和删除文件,C# 编程语言都提供了强大且易于使用的文件操作功能。本篇博客将介绍如何使用C#来进行基本的文件操作。
36 0
|
NoSQL C# 数据库
基于C#的ArcEngine二次开发29:GDB文件操作及异常处理(下)
基于C#的ArcEngine二次开发29:GDB文件操作及异常处理
|
NoSQL 定位技术 API
基于C#的ArcEngine二次开发29:GDB文件操作及异常处理(上)
基于C#的ArcEngine二次开发29:GDB文件操作及异常处理
基于C#的ArcEngine二次开发29:GDB文件操作及异常处理(上)
C#编程-111:文件操作之获取基本信息
C#编程-111:文件操作之获取基本信息
C#编程-111:文件操作之获取基本信息
C#编程-110:文件操作File静态类
C#编程-110:文件操作File静态类
C#编程-110:文件操作File静态类
|
C#
30天C#基础巩固------集合,File(文件操作 ),Encoding处理字符集
30天C#基础巩固------集合,File(文件操作 ),Encoding处理字符集
100 0
30天C#基础巩固------集合,File(文件操作 ),Encoding处理字符集
|
缓存 开发框架 运维
C#好代码学习笔记(1):文件操作、 读取文件、Debug/Trace类、Conditional条件编译、CLS
C#好代码学习笔记(1):文件操作、 读取文件、Debug/Trace类、Conditional条件编译、CLS
197 0
C#(三十七)之基于流的文件操作(FileStream)
本篇内容记录了FileStream类属性和方法。
278 0
C#(三十七)之基于流的文件操作(FileStream)
|
C# Windows
☀️ 学会编程入门必备 C# 最基础知识介绍—— C# 高级文件操作(文本文件的读写、二进制文件的读写、Windows 文件系统的操作)
前言🙏 C# 文本文件的读写👇 StreamWriter 类 C# 二进制文件的读写👏 BinaryReader 类 BinaryWriter 类 C# Windows 文件系统的操作👋 DirectoryInfo 类 FileInfo 类
☀️ 学会编程入门必备 C# 最基础知识介绍—— C# 高级文件操作(文本文件的读写、二进制文件的读写、Windows 文件系统的操作)