代码改变世界

CodeSmith模板引擎系列二--文件目录树

2010-07-14 11:21  破狼  阅读(1658)  评论(5编辑  收藏  举报

   今天网上Google了一下,关于CodeSmith的资料已经很全了,其中有TerryLee努力学习的小熊 两位大牛的很详尽,所以我也不准备把CodeSmith讲的很细致了,如果是新手学习者可以参考上面两位大牛的CodeSmith文章,CodeSmith的语法与ASP语法接近,语言可以选择我们的c#,所以学习起来很轻松。今天就写一个简单的文件目录树结构的递归模板。

Template Code:

 

代码
<%@ CodeTemplate Language="C#" TargetLanguage="Text" Src="" Inherits="" Debug="False" 
   Description
="Template description here." %>
<%@ Assembly Name="System.Data" %>
<%@ Import Namespace="System.Data" %>
<%@ Assembly Name="System" %>
<%@ Import Namespace="System.IO" %> 

-----------------------------------------------------------------
 
-- Date Created: <%= DateTime.Now.ToLongDateString() %>
 
-- Createdy:   B Generated by Wolf
 
-----------------------------------------------------------------
 
<script runat="template">
        
private string path;
        [Editor(
typeof(System.Windows.Forms.Design.FolderNameEditor),

         
typeof(System.Drawing.Design.UITypeEditor))] 
        
public string Path
        {
            
get{return this.path;}    
            
set{this.path=value;}
        }
        
public void GetFolderString(string fload,string indexStr)
        {
            
if(string.IsNullOrEmpty(fload))
                
throw new System.ArgumentNullException("fload");
            Response.WriteLine(indexStr
+fload);
            indexStr
+="----";            
            
if(System.IO.Directory.Exists(fload))
            {
                
string[] childfolder= System.IO.Directory.GetDirectories(fload);
                
string[] childfile= System.IO.Directory.GetFiles(fload);
                
foreach(string item in childfolder)
                {
                    
this.GetFolderString(item,indexStr);
                }
                
foreach(string item in childfile)
                {
                    
this.GetFolderString(item,indexStr);
                }
            }
        }
        
public void Start()
        {
            
this.GetFolderString(this.path,"");
        }
</script>
<% this.Start(); %>

 

 

模板生成代码比较简单,就不在这里多讲述了,只是拿来展示一下CodeSmith模板对于生成基于Ascii语言文件的强大威力:
image
内容比较少今天就到这里。