几个遍历文件夹的例子

    技术2022-05-11  61

    一、使用SPFolderCollection以及SPFolder对象分层次显示文档列表http://dev.csdn.net/develop/article/41/41741.shtm

    Shaerpoint的文档库的功能很强大,显示文档列表的方式也很多,我们可以使用系统的视图显示文档,我们也可以定义视图来显示文档列表。在系统提供的视图中您可以选择是否显示文件夹。但是,我们有时候希望向察看本地资源管理器那样的分层查看文档列表,即展现出文档以及文档夹之间的层次关系。我这里介绍使用SPFoldercollection 和SPFolder对象模型来实现这个功能。

    首先,由于我们的Webpart可能要用于显示不同的文档库,所以,我们自定义一个属性用于传递您要显示的文档库的名称: namespace WPDocLibTree { /// <summary> /// Description for WebPart1. /// </summary> [DefaultProperty("Text"), ToolboxData("<{0}:WPDocLibTree runat=server></{0}:WPDocLibTree>"), XmlRoot(Namespace="WPDocLibTree")] public class WPDocLibTree : Microsoft.SharePoint.WebPartPages.WebPart { private const string defaultText = "";   private string text = defaultText; private string _myDoc="";   [Browsable(true), Category("Miscellaneous"), DefaultValue(defaultText), WebPartStorage(Storage.Personal), FriendlyName("Text"), Description("Text Property")] public string Text { get { return text; }   set { text = value; } }   //文档库名称 [Category("文档库定义")] [DefaultValue("")] [WebPartStorage(Storage.Personal)] [FriendlyNameAttribute("文档库名称")] [Description("请输入要显示的文档库德名称")] [Browsable(true)] [XmlElement(ElementName="myDoc")] public string myDoc { get { return _myDoc; } set { _myDoc=value; } }   然后,在RenderWebPart来显示我们的文档列表:   protected override void RenderWebPart(HtmlTextWriter output) { //首先,我们通过下列语句格式化我们的文档列表: output.Write("<style><!--.folder1 { font-size: 10pt; color: #000080;margin-left: 50; font-weight:bold;}"); output.Write (".file1 { font-size: 10pt; color: #3366CC;margin-left: 50; }"); output.Write(".folder2 { font-size: 10pt; color: #000080;margin-left: 70; font-weight:bold}"); output.Write (".file2 { font-size: 10pt; color: #3366CC;margin-left: 70 }"); output.Write(".folder3 { font-size: 10pt; color: #000080;margin-left: 90; font-weight:bold}"); output.Write (".file3 { font-size: 10pt; color: #3366CC;margin-left: 90 }"); output.Write(".folder4 { font-size: 10pt; color: #000080;margin-left: 110; font-weight:bold}"); output.Write (".file4 { font-size: 10pt; color: #3366CC;margin-left: 110 }"); output.Write ("--></style>"); //打开当前站点 SPWeb site=SPControl.GetContextWeb(Context); //获取站点中的所有文件夹 SPFolderCollection folders=site.Folders; //获取指定的文档库(文件夹) SPFolder folder=folders[_myDoc]; //获取所有文档 SPFileCollection files=folder.Files; for(int i=0;i<files.Count;i++) { output.Write("<a class='file1' target='_blank' href=' "+files[i].ServerRelativeUrl.ToString()+"'><img border=/"0/" src=/"../_layouts/images/keyword.gif/">  "+files[i].Name.ToString()+"</a><br>"); } //检查是否有子文件夹 SPFolderCollection subFolders=folder.SubFolders ; if(subFolders.Count>1) {  // 显示子文件夹       foreach(SPFolder subFolder in subFolders)     { //过滤掉系统文件夹“forms” if(subFolder.Name.ToString().ToUpper()!="FORMS") { //folder=subFolder; output.Write("<a class='folder1' target='_blank' href=' "+subFolder.ServerRelativeUrl.ToString()+"'><img border=/"0/" src=/"../_layouts/images/folder.gif/">  "+subFolder.Name.ToString()+"</a><br>"); SPFileCollection files1=subFolder.Files; //显示子文件夹中的文件 foreach(SPFile file1 in files1) { output.Write("<a class='file2' target='_blank' href=' "+file1.ServerRelativeUrl.ToString()+"'><img border=/"0/" src=/"../_layouts/images/keyword.gif/">  "+file1.Name.ToString()+"</a><br>");   } }     } }   二、遍历当前文件夹下的文件添加Microsoft.Scripting.Runtime组件 Imports Scripting  Sub FindFile()         Dim strFileName As String         Dim objFso As FileSystemObject         Dim objFiles As Files         Dim objFile As File         objFso = CreateObject("Scripting.FileSystemObject")         objFiles = objFso.GetFolder("D:/mmsk/").Files         If objFiles.Count = 0 Then             MsgBox("没有任何文件!", vbInformation, "提示")             GoTo Err         End If         For Each objFile In objFiles             strFileName = objFile.Name             Response.Write(strFileName)             Response.Write("<br>")         Next Err:         objFile = Nothing         objFiles = Nothing         objFso = Nothing         Exit Sub     End Sub   三、遍历目录以及目录下文件添加Microsoft.Scripting.Runtime组件 Imports Scripting Function bianli(ByVal path)         Dim fso = Server.CreateObject("scripting.filesystemobject")         On Error Resume Next         Dim objFolder = fso.GetFolder(path)         Dim objSubFolders = objFolder.Subfolders         Dim objSubFolder         For Each objSubFolder In objSubFolders             Dim nowpath = path + "/" + objSubFolder.name             Response.Write(nowpath)             Dim objFiles = objSubFolder.Files             Dim objFile             For Each objFile In objFiles                 Response.Write("<br>---")                 Response.Write(objFile.name)             Next             Response.Write("<p>")             bianli(nowpath) '递归         Next         objFolder = Nothing         objSubFolders = Nothing         fso = Nothing     End Function   bianli("D:/mmsk")   四、 使用.Net遍历指定目录下的所有文件 Imports System.IO  Function GetFiles(ByVal path As String)         '获取当前目录下的所有文件并显示         Dim files As String() = Directory.GetFiles(path)         Dim s As String         For Each s In files             Response.Write(s + "<br>")         Next         '获取当前目录下的所有子目录并进新递归调用         Dim dir As String() = Directory.GetDirectories(path)         Dim t As String         For Each t In dir             GetFiles(t)         Next     End Function  GetFiles("D:/mmsk") 五、.net遍历所有当前及下级目录,并记录为XML文件 using System;using System.Drawing;using System.Collections;using System.ComponentModel;using System.Windows.Forms;using System.Data;using System.IO;using System.Xml;namespace WindowsApplication2{ /// <summary> /// Form1 的摘要说明。 /// </summary> public class Form1 : System.Windows.Forms.Form {  private System.Windows.Forms.Button button1;  /// <summary>  /// 必需的设计器变量。  /// </summary>  private System.ComponentModel.Container components = null;  const  string mypath=@"D:/nba2004 ";  XmlDocument doc=new XmlDocument();   public Form1()  {   //   // Windows 窗体设计器支持所必需的   //   InitializeComponent();    //   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码   //  }   /// <summary>  /// 清理所有正在使用的资源。  /// </summary>  protected override void Dispose( bool disposing )  {   if( disposing )   {    if (components != null)     {     components.Dispose();    }   }   base.Dispose( disposing );  }   #region Windows 窗体设计器生成的代码  /// <summary>  /// 设计器支持所需的方法 - 不要使用代码编辑器修改  /// 此方法的内容。  /// </summary>  private void InitializeComponent()  {   this.button1 = new System.Windows.Forms.Button();   this.SuspendLayout();   //    // button1   //    this.button1.Location = new System.Drawing.Point(192, 232);   this.button1.Name = "button1";   this.button1.Size = new System.Drawing.Size(88, 24);   this.button1.TabIndex = 0;   this.button1.Text = "button1";   this.button1.Click += new System.EventHandler(this.button1_Click1);   //    // Form1   //    this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);   this.ClientSize = new System.Drawing.Size(292, 273);   this.Controls.Add(this.button1);   this.Name = "Form1";   this.Text = "Form1";   this.ResumeLayout(false);   }  #endregion   /// <summary>  /// 应用程序的主入口点。  /// </summary>  [STAThread]  static void Main()   {   Application.Run(new Form1());  }        private void button1_Click1(object sender, System.EventArgs e)   {        string MyPath=mypath.ToUpper();    doc.LoadXml("<FileInfo Name='"+MyPath+"'></FileInfo>");    GetFileInfo(MyPath,doc.DocumentElement);    doc.Save(@"d:/fileinfo.xml");   }  private void GetFileInfo(string strpath,System.Xml.XmlNode node)  {   DirectoryInfo DirInfo=new DirectoryInfo(strpath);   foreach(DirectoryInfo dirinfo in DirInfo.GetDirectories())   {    XmlElement elem = doc.CreateElement("dir");    elem.SetAttribute("Name",dirinfo.Name);    elem.SetAttribute("LastWriteTime",dirinfo.LastWriteTime.ToString());    node.AppendChild(elem);     GetFileInfo(dirinfo.FullName,elem);   }     foreach(FileInfo fileinfo in DirInfo.GetFiles())   {    XmlElement elem = doc.CreateElement("file");    elem.SetAttribute("Name",fileinfo.Name);    elem.SetAttribute("LastWriteTime",fileinfo.LastWriteTime.ToString());    elem.SetAttribute("Length",fileinfo.Length.ToString());    node.AppendChild(elem);   }  }   } } 首先,由于我们的Webpart可能要用于显示不同的文档库,所以,我们自定义一个属性用于传递您要显示的文档库的名称: namespace WPDocLibTree { /// <summary> /// Description for WebPart1. /// </summary> [DefaultProperty("Text"), ToolboxData("<{0}:WPDocLibTree runat=server></{0}:WPDocLibTree>"), XmlRoot(Namespace="WPDocLibTree")] public class WPDocLibTree : Microsoft.SharePoint.WebPartPages.WebPart { private const string defaultText = "";   private string text = defaultText; private string _myDoc="";   [Browsable(true), Category("Miscellaneous"), DefaultValue(defaultText), WebPartStorage(Storage.Personal), FriendlyName("Text"), Description("Text Property")] public string Text { get { return text; }   set { text = value; } }   //文档库名称 [Category("文档库定义")] [DefaultValue("")] [WebPartStorage(Storage.Personal)] [FriendlyNameAttribute("文档库名称")] [Description("请输入要显示的文档库德名称")] [Browsable(true)] [XmlElement(ElementName="myDoc")] public string myDoc { get { return _myDoc; } set { _myDoc=value; } }   然后,在RenderWebPart来显示我们的文档列表:   protected override void RenderWebPart(HtmlTextWriter output) { //首先,我们通过下列语句格式化我们的文档列表: output.Write("<style><!--.folder1 { font-size: 10pt; color: #000080;margin-left: 50; font-weight:bold;}"); output.Write (".file1 { font-size: 10pt; color: #3366CC;margin-left: 50; }"); output.Write(".folder2 { font-size: 10pt; color: #000080;margin-left: 70; font-weight:bold}"); output.Write (".file2 { font-size: 10pt; color: #3366CC;margin-left: 70 }"); output.Write(".folder3 { font-size: 10pt; color: #000080;margin-left: 90; font-weight:bold}"); output.Write (".file3 { font-size: 10pt; color: #3366CC;margin-left: 90 }"); output.Write(".folder4 { font-size: 10pt; color: #000080;margin-left: 110; font-weight:bold}"); output.Write (".file4 { font-size: 10pt; color: #3366CC;margin-left: 110 }"); output.Write ("--></style>"); //打开当前站点 SPWeb site=SPControl.GetContextWeb(Context); //获取站点中的所有文件夹 SPFolderCollection folders=site.Folders; //获取指定的文档库(文件夹) SPFolder folder=folders[_myDoc]; //获取所有文档 SPFileCollection files=folder.Files; for(int i=0;i<files.Count;i++) { output.Write("<a class='file1' target='_blank' href=' "+files[i].ServerRelativeUrl.ToString()+"'><img border=/"0/" src=/"../_layouts/images/keyword.gif/">  "+files[i].Name.ToString()+"</a><br>"); } //检查是否有子文件夹 SPFolderCollection subFolders=folder.SubFolders ; if(subFolders.Count>1) {  // 显示子文件夹        foreach(SPFolder subFolder in subFolders)     { //过滤掉系统文件夹“forms” if(subFolder.Name.ToString().ToUpper()!="FORMS") { //folder=subFolder; output.Write("<a class='folder1' target='_blank' href=' "+subFolder.ServerRelativeUrl.ToString()+"'><img border=/"0/" src=/"../_layouts/images/folder.gif/">  "+subFolder.Name.ToString()+"</a><br>"); SPFileCollection files1=subFolder.Files; //显示子文件夹中的文件 foreach(SPFile file1 in files1) { output.Write("<a class='file2' target='_blank' href=' "+file1.ServerRelativeUrl.ToString()+"'><img border=/"0/" src=/"../_layouts/images/keyword.gif/">  "+file1.Name.ToString()+"</a><br>");   } }     } }    

    最新回复(0)