随笔- 3  文章- 5  评论- 14 

 

     项目中需要一个网络共享文件夹,在网上找了好多代码没有合适的,自己编写、整理了一个。

     希望对大家有用。

 

提供事例代码下载,代码中还包含了一个我常用的日至类。

http://files.cnblogs.com/Leodr/FileManagerDemo.rar

 

在web.config里配置,文件的限制信息

 

BrowseFiles.aspx

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="BrowseFiles.aspx.cs" enableEventValidation="false"
    Inherits
="CommonPage_FileManager_BrowseFiles" 
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    
<title>无标题页</title>
    
<link href="../FileManager/StyleBrowseFile.css" rel="stylesheet" type="text/css" />
    
<script language="javascript">

        
function CreateDir()
        
{
            dirName 
= prompt('输入要创建的目录名称:','新文件夹');

            
if ((dirName) && (dirName!=""))
            
{
                document.forms[
'BrowseFiles'].elements['funcParam'].value = dirName;
                __doPostBack(
'CreateDir''');
            }

        }

        
        
function Download(path)
        
{
                document.forms[
'BrowseFiles'].elements['funcParam'].value = path;
                __doPostBack(
'Download''');
        }

        
        
function Delete()
        
{
            
return confirm('确认要删除所选的文件/文件夹吗?')
            
//    __doPostBack('Delete','');
        }

        
function Rename(path)
        
{
            newName 
= prompt('输入文件夹/文件的新名称:','');

            
if ((newName) && (newName!=""))
            
{
                document.forms[
'BrowseFiles'].elements['funcParam'].value = path;
                document.forms[
'BrowseFiles'].elements['funcExtraParam'].value = newName;
                __doPostBack(
'Rename''');
            }

        }

    
</script>

</head>
<body>
    
<form id="BrowseFiles" method="post" runat="server" enctype="multipart/form-data">
        
<input type="hidden" id="funcParam" runat="server" name="funcParam">
        
<input type="hidden" id="funcExtraParam" runat="server" name="funcExtraParam">
        
<asp:Table runat="server" CssClass="TableHeader" Width="100%" ID="Table1">
            
<asp:TableRow>
                
<asp:TableCell Width="36">
                    
<asp:Image runat="server" Height="25" Width="25" ImageUrl="./Images/OpenFolder.gif"
                        ID
="Image1" NAME="Image1"></asp:Image>
                
</asp:TableCell>
                
<asp:TableCell>
                    
<asp:Label runat="server" ID="FolderDescription"></asp:Label>
                
</asp:TableCell>
                
<asp:TableCell Width="140px">
                    操作:
<href="javascript:CreateDir();"><img border="0" src="./Images/NewFolder.gif"
                        alt
="创建一个新目录" height="20" width="20"></a>
                    
<asp:LinkButton ID="CreateDir" runat="server" OnClick="CreateDir_Click" />
                    
<%--<a href="javascript:Delete();"><img border="0" src="./Images/Delete.gif" Alt="删除选择的文件/文件夹" height="20" width="20"></a>
                        
--
%>
                    
<asp:ImageButton ImageUrl="./Images/Delete.gif" ToolTip="删除选择的文件/文件夹" Height="20"
                        Width
="20" ID="ImageButton1" runat="server" OnClientClick="Delete();" OnClick="Delete_Click" /><asp:LinkButton
                            
ID="Delete" runat="server" OnClick="Delete_Click" Visible="False" />
                            
<asp:LinkButton ID="Rename" runat="server" OnClick="Rename_Click" Visible="False" />
                             
<asp:LinkButton ID="Download" runat="server" OnClick="Download_Click" Visible="False" />
                            
</asp:TableCell>
            
</asp:TableRow>
        
</asp:Table>
        
<asp:Table ID="FoldersAndFiles" runat="server" CssClass="Grid_General" Width="100%">
            
<asp:TableRow CssClass="Grid_Header">
                
<asp:TableCell Width="36px" Font-Bold="True" />
                
<asp:TableCell Text="名称" Font-Bold="True" />
                
<asp:TableCell Width="30px" Font-Bold="True" />
                
<asp:TableCell Width="40px" Font-Bold="True" />
                
<asp:TableCell Text="大小" Width="80px" Font-Bold="True" HorizontalAlign="Right" />
                
<asp:TableCell Text="创建时间" Width="140px" Font-Bold="True" />
                
<asp:TableCell Text="修改时间" Width="140px" Font-Bold="True" />
            
</asp:TableRow>
        
</asp:Table>
        
<br>
        
<asp:Table runat="server" ID="Table2">
            
<asp:TableRow>
                
<asp:TableCell Width="80px" Font-Bold="True" Text="上传文件:" />
                
<asp:TableCell>
                    
<input id="UploadedFile" runat="server" class="LongButton" name="UploadedFile" size="35"
                        type
="file">
                
</asp:TableCell>
                
<asp:TableCell>
                    
<asp:Button ID="Upload" OnClick="Upload_Click" runat="server" CssClass="Button" Text="上 传">
                    
</asp:Button>
                
</asp:TableCell>
            
</asp:TableRow>
        
</asp:Table>
        
&nbsp;<br>
        
<asp:Label ID="StatusMessage" runat="server" CssClass="StatusMessage" Visible="False"
            Width
="100%" />
        
<asp:Label ID="FolderStyle" runat="Server" Text="Grid_Item" Visible="false" />
        
<asp:Label ID="FileStyle" runat="Server" Text="Grid_AlternatingItem" Visible="false" />
    
</form>
</body>
</html>

 

BrowseFiles.aspx.cs

 

 

  1using System;
  2using System.Data;
  3using System.Configuration;
  4using System.Collections;
  5using System.Web;
  6using System.Web.Security;
  7using System.Web.UI;
  8using System.Web.UI.WebControls;
  9using System.Web.UI.WebControls.WebParts;
 10using System.Web.UI.HtmlControls;
 11using LEO.Common;
 12
 13using System.IO;
 14
 15public partial class CommonPage_FileManager_BrowseFiles : BasePage
 16{
 17    private string folderPath;
 18    private string folderPathDefault;
 19    private string[] extensions = new string[]{".arj"".asa",".asax"".ascx"".asmx"".asp"".aspx"".au"".avi"".bat"".bmp"
 20                                                      ".cab"".chm"".com"".config"".cs"".css"".disco"".dll"".doc"
 21                                                      ".exe"".gif"".hlp"".htm"".html"".jpg",".png"".inc"".ini"
 22                                                      ".log"".mdb"".mid"".midi"".mov"".mp3"".mpg"".mpeg",
 23                                                      ".pdf"".ppt"".sys"".txt"".tif"".vb"".vbs"".vsdisco"
 24                                                      ".wav"".wri"".swf"".xls"".xml"".zip",".rar"}
;
 25    protected void Page_Load(object sender, EventArgs e)
 26    {
 27        //初始化文件夹路径
 28        folderPathDefault = String.Format("{0}/{1}", Request.ApplicationPath.ToString(), ConfigurationManager.AppSettings["folderPath"].ToString());
 29        if (!Directory.Exists(folderPathDefault))
 30            Directory.CreateDirectory(Server.MapPath(folderPathDefault));
 31        folderPath = Server.UrlDecode(Request.Params["Folder"]);
 32        
 33        if (folderPath == null || folderPath == "/")
 34            folderPath = folderPathDefault;
 35        // 去除文件夹末尾的"/".
 36        else if (folderPath.EndsWith("/"))
 37            folderPath = folderPath.Substring(0, folderPath.Length - 1);
 38        
 39        // 显示文件路径
 40        FolderDescription.Text = "文件路径: " + folderPath.Substring(folderPathDefault.Length);
 41
 42        // 实际文件夹路径    "<br>Physical folder: " + Server.MapPath(folderPath);
 43        FillFoldersAndFilesTable();
 44    }

 45
 46
 47    /****************************************************************************
 48    /扫描当前文件夹,添加所有子目录和文件 
 49    /添加文件链接、图标、文件夹结构, 和其他资料,如创建日期,大小等。
 50    /****************************************************************************/

 51    private void FillFoldersAndFilesTable()
 52    {
 53        string location;
 54
 55        DirectoryInfo parentDir;
 56        DirectoryInfo[] childDirs;
 57        FileInfo[] childFiles;
 58        try
 59        {
 60            parentDir = new DirectoryInfo(Server.MapPath(folderPath));
 61            //得到所有的文件夹、子目录
 62            childDirs = parentDir.GetDirectories();
 63            childFiles = parentDir.GetFiles();
 64        }

 65        catch (Exception exc)
 66        {
 67            StatusMessage.Text = exc.Message;
 68            StatusMessage.Visible = true;
 69            Logger.Log(Logger.ERROR, "初始化共享文件夹 :" + exc.Message);
 70            return;
 71        }

 72
 73        TableRow rowItem;
 74        TableCell cellItemIcon;
 75        TableCell cellItemLink;
 76        TableCell cellSize;
 77        TableCell cellDownload;
 78        TableCell cellOperations;
 79        TableCell cellCreated;
 80        TableCell cellLastModified;
 81        HyperLink linkRename;
 82        HyperLink linkItem;
 83        HyperLink linkDownload;
 84        CheckBox checkItem;
 85        //     HyperLink linkSetAttribs;
 86        //     Label labelAttributes;
 87        System.Web.UI.WebControls.Image imgItemIcon;
 88
 89        Style styleFolderRow = new Style();
 90        styleFolderRow.CssClass = FolderStyle.Text;
 91        Style styleFileRow = new Style();
 92        styleFileRow.CssClass = FileStyle.Text;
 93        Style styleLink = new Style();
 94        styleLink.CssClass = "GridLink";
 95
 96        // 如果目录不是共享文件的根目录增加向上一级的链接
 97        if (folderPath != folderPathDefault)
 98        {
 99            rowItem = new TableRow();
100            cellItemIcon = new TableCell();
101            cellItemLink = new TableCell();
102            linkItem = new HyperLink();
103            imgItemIcon = new System.Web.UI.WebControls.Image();
104
105            // 增加向上的图片链接
106            imgItemIcon.ImageUrl = "./Images/ParentFolder.gif";
107            cellItemIcon.Controls.Add(imgItemIcon);
108            cellItemIcon.HorizontalAlign = HorizontalAlign.Right;
109
110            // 增加到父级目录的链接
111            linkItem.Text = " ";
112            int lastSlashIndex = folderPath.LastIndexOf("/");
113            location = folderPath.Substring(0, lastSlashIndex);
114            if (location.Length == 0)
115                location = Request.ApplicationPath.ToString();
116            linkItem.NavigateUrl = "BrowseFiles.aspx?Folder=" + Server.UrlEncode(location);
117            linkItem.ApplyStyle(styleLink);
118            cellItemLink.Controls.Add(linkItem);
119
120            // 添加单元格到行
121            rowItem.Cells.Add(cellItemIcon);
122            rowItem.Cells.Add(cellItemLink);
123            rowItem.Cells.Add(new TableCell());
124            rowItem.Cells.Add(new TableCell());
125