ASP.NET中常用功能代码总结(5)——文件操作篇

ASP.NET中常用功能代码总结(5——文件操作篇<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

整理:Terrylee

一.读取文本文件

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

 4 None.gif private   void  ReadFromTxtFile()
 5 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 6InBlock.gif    if(filePath.PostedFile.FileName != "")
 7ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.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.gifContractedSubBlock.gif        dot.gif{
13InBlock.gif            Response.Write("请选择文本文件");
14ExpandedSubBlockEnd.gif        }

15InBlock.gif        else
16ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.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 ContractedBlock.gif /**/ /// <summary>
  2InBlock.gif/// 获取文件列表
  3ExpandedBlockEnd.gif/// </summary>
  4 None.gif private   void  GetFileList()
  5 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
  6InBlock.gif    string strCurDir,FileName,FileExt;
  7InBlock.gif    
  8ExpandedSubBlockStart.gifContractedSubBlock.gif    /**////文件大小
  9InBlock.gif    long FileSize;
 10InBlock.gif    
 11ExpandedSubBlockStart.gifContractedSubBlock.gif    /**////最后修改时间;
 12InBlock.gif    DateTime FileModify;
 13InBlock.gif
 14ExpandedSubBlockStart.gifContractedSubBlock.gif    /**////初始化
 15InBlock.gif    if(!IsPostBack)
 16ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 17ExpandedSubBlockStart.gifContractedSubBlock.gif        /**////初始化时,默认为当前页面所在的目录
 18InBlock.gif        strCurDir = Server.MapPath(".");
 19InBlock.gif        lblCurDir.Text = strCurDir;
 20InBlock.gif        txtCurDir.Text = strCurDir;
 21ExpandedSubBlockEnd.gif    }

 22InBlock.gif    else
 23ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.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.gifContractedSubBlock.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.gifContractedSubBlock.gif    /**////针对当前目录建立目录引用对象
 51InBlock.gif    DirectoryInfo dirInfo = new DirectoryInfo(txtCurDir.Text);
 52InBlock.gif    
 53ExpandedSubBlockStart.gifContractedSubBlock.gif    /**////循环判断当前目录下的文件和目录
 54InBlock.gif    foreach(FileSystemInfo fsi in dirInfo.GetFileSystemInfos())
 55ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 56InBlock.gif        FileName = "";
 57InBlock.gif        FileExt = "";
 58InBlock.gif        FileSize = 0;
 59InBlock.gif        
 60ExpandedSubBlockStart.gifContractedSubBlock.gif        /**////如果是文件
 61InBlock.gif        if(fsi is FileInfo)
 62ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 63InBlock.gif            fi = (FileInfo)fsi;
 64InBlock.gif            
 65ExpandedSubBlockStart.gifContractedSubBlock.gif            /**////取得文件名
 66InBlock.gif            FileName = fi.Name;
 67InBlock.gif            
 68ExpandedSubBlockStart.gifContractedSubBlock.gif            /**////取得文件的扩展名
 69InBlock.gif            FileExt = fi.Extension;
 70InBlock.gif            
 71ExpandedSubBlockStart.gifContractedSubBlock.gif            /**////取得文件的大小
 72InBlock.gif            FileSize = fi.Length;
 73InBlock.gif            
 74ExpandedSubBlockStart.gifContractedSubBlock.gif            /**////取得文件的最后修改时间
 75InBlock.gif            FileModify = fi.LastWriteTime;
 76ExpandedSubBlockEnd.gif        }

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

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

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

四.写入日志文件

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

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

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

46ExpandedBlockEnd.gif}

五.创建HTML文件

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

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

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

23ExpandedSubBlockEnd.gif    }

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

29ExpandedSubBlockStart.gifContractedSubBlock.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.gifContractedSubBlock.gif    /**////根据上面新的内容生成html文件
37InBlock.gif    try
38ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
39ExpandedSubBlockStart.gifContractedSubBlock.gif        /**////指定要生成的HTML文件
40InBlock.gif        string fname = Server.MapPath("createHTML"+"\\" + DateTime.Now.ToString("yyyymmddhhmmss"+ ".html";
41InBlock.gif        
42ExpandedSubBlockStart.gifContractedSubBlock.gif        /**////替换html模版文件里的标记为新的内容
43InBlock.gif        for(int i=0;i < 5;i++)
44ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
45InBlock.gif            strhtml.Replace("$htmlkey["+i+"]",newContent[i]);
46ExpandedSubBlockEnd.gif        }

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

61InBlock.gif        
62ExpandedSubBlockStart.gifContractedSubBlock.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.gifContractedSubBlock.gif    dot.gif
68InBlock.gif        Response.Write (err.ToString());
69ExpandedSubBlockEnd.gif    }

70ExpandedBlockEnd.gif}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值