FileManager(文件管理类)

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Web;

[Serializable]
public class FileItem
{
    public FileItem()
    { }

    #region 私有字段
    private string _Name;
    private string _FullName;
    private DateTime _CreationDate;
    private bool _IsFolder;
    private long _Size;
    private DateTime _LastAccessDate;
    private DateTime _LastWriteDate;
    private int _FileCount;
    private int _SubFolderCount;
    #endregion

    #region 公有属性
    /// <summary>
    /// 名称
    /// </summary>
    public string Name
    {
        get { return _Name; }
        set { _Name = value; }
    }

    /// <summary>
    /// 文件或目录的完整目录
    /// </summary>
    public string FullName
    {
        get { return _FullName; }
        set { _FullName = value; }
    }

    /// <summary>
    ///  创建时间
    /// </summary>
    public DateTime CreationDate
    {
        get { return _CreationDate; }
        set { _CreationDate = value; }
    }

    public bool IsFolder
    {
        get { return _IsFolder; }
        set { _IsFolder = value; }
    }

    /// <summary>
    /// 文件大小
    /// </summary>
    public long Size
    {
        get { return _Size; }
        set { _Size = value; }
    }

    /// <summary>
    /// 上次访问时间
    /// </summary>
    public DateTime LastAccessDate
    {
        get { return _LastAccessDate; }
        set { _LastAccessDate = value; }
    }

    /// <summary>
    /// 上次读写时间
    /// </summary>
    public DateTime LastWriteDate
    {
        get { return _LastWriteDate; }
        set { _LastWriteDate = value; }
    }

    /// <summary>
    /// 文件个数
    /// </summary>
    public int FileCount
    {
        get { return _FileCount; }
        set { _FileCount = value; }
    }

    /// <summary>
    /// 目录个数
    /// </summary>
    public int SubFolderCount
    {
        get { return _SubFolderCount; }
        set { _SubFolderCount = value; }
    }
    #endregion
}

public class FileManager
{
    #region 构造函数
    private static string strRootFolder;
    static FileManager()
    {
        strRootFolder = HttpContext.Current.Request.PhysicalApplicationPath + "File\\";
        strRootFolder = strRootFolder.Substring(0, strRootFolder.LastIndexOf(@"\"));
    }
    #endregion

    #region 目录
    /// <summary>
    /// 读根目录
    /// </summary>
    public static string GetRootPath()
    {
        return strRootFolder;
    }

    /// <summary>
    /// 写根目录
    /// </summary>
    public static void SetRootPath(string path)
    {
        strRootFolder = path;
    }

    /// <summary>
    /// 读取目录列表
    /// </summary>
    public static List<FileItem> GetDirectoryItems()
    {
        return GetDirectoryItems(strRootFolder);
    }

    /// <summary>
    /// 读取目录列表
    /// </summary>
    public static List<FileItem> GetDirectoryItems(string path)
    {
        List<FileItem> list = new List<FileItem>();
        string[] folders = Directory.GetDirectories(path);
        foreach (string s in folders)
        {
            FileItem item = new FileItem();
            DirectoryInfo di = new DirectoryInfo(s);
            item.Name = di.Name;
            item.FullName = di.FullName;
            item.CreationDate = di.CreationTime;
            item.IsFolder = false;
            list.Add(item);
        }
        return list;
    }
    #endregion

    #region 文件
    /// <summary>
    /// 读取文件列表
    /// </summary>
    public static List<FileItem> GetFileItems()
    {
        return GetFileItems(strRootFolder);
    }

    /// <summary>
    /// 读取文件列表
    /// </summary>
    public static List<FileItem> GetFileItems(string path)
    {
        List<FileItem> list = new List<FileItem>();
        string[] files = Directory.GetFiles(path);
        foreach (string s in files)
        {
            FileItem item = new FileItem();
            FileInfo fi = new FileInfo(s);
            item.Name = fi.Name;
            item.FullName = fi.FullName;
            item.CreationDate = fi.CreationTime;
            item.IsFolder = true;
            item.Size = fi.Length;
            list.Add(item);
        }
        return list;
    }

    /// <summary>
    /// 创建文件
    /// </summary>
    public static bool CreateFile(string filename, string path)
    {
        try
        {
            FileStream fs = File.Create(path + "\\" + filename);
            fs.Close();
            return true;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 创建文件
    /// </summary>
    public static bool CreateFile(string filename, string path, byte[] contents)
    {
        try
        {
            FileStream fs = File.Create(path + "\\" + filename);
            fs.Write(contents, 0, contents.Length);
            fs.Close();
            return true;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 读取文件
    /// </summary>
    public static string OpenText(string parentName)
    {
        StreamReader sr = File.OpenText(parentName);
        StringBuilder output = new StringBuilder();
        string rl;
        while ((rl = sr.ReadLine()) != null)
        {
            output.Append(rl);
        }
        sr.Close();
        return output.ToString();
    }

    /// <summary>
    /// 读取文件信息
    /// </summary>
    public static FileItem GetItemInfo(string path)
    {
        FileItem item = new FileItem();
        if (Directory.Exists(path))
        {
            DirectoryInfo di = new DirectoryInfo(path);
            item.Name = di.Name;
            item.FullName = di.FullName;
            item.CreationDate = di.CreationTime;
            item.IsFolder = true;
            item.LastAccessDate = di.LastAccessTime;
            item.LastWriteDate = di.LastWriteTime;
            item.FileCount = di.GetFiles().Length;
            item.SubFolderCount = di.GetDirectories().Length;
        }
        else
        {
            FileInfo fi = new FileInfo(path);
            item.Name = fi.Name;
            item.FullName = fi.FullName;
            item.CreationDate = fi.CreationTime;
            item.LastAccessDate = fi.LastAccessTime;
            item.LastWriteDate = fi.LastWriteTime;
            item.IsFolder = false;
            item.Size = fi.Length;
        }
        return item;
    }

    /// <summary>
    /// 写入一个新文件,在文件中写入内容,然后关闭文件。如果目标文件已存在,则改写该文件。
    /// </summary>
    public static bool WriteAllText(string parentName, string contents)
    {
        try
        {
            File.WriteAllText(parentName, contents, Encoding.Unicode);
            return true;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 删除文件
    /// </summary>
    public static bool DeleteFile(string path)
    {
        try
        {
            File.Delete(path);
            return true;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 移动文件
    /// </summary>
    public static bool MoveFile(string oldPath, string newPath)
    {
        try
        {
            File.Move(oldPath, newPath);
            return true;
        }
        catch
        {
            return false;
        }
    }
    #endregion

    #region 文件夹
    /// <summary>
    /// 创建文件夹
    /// </summary>
    public static void CreateFolder(string name, string parentName)
    {
        DirectoryInfo di = new DirectoryInfo(parentName);
        di.CreateSubdirectory(name);
    }

    /// <summary>
    /// 删除文件夹
    /// </summary>
    public static bool DeleteFolder(string path)
    {
        try
        {
            Directory.Delete(path);
            return true;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 移动文件夹
    /// </summary>
    public static bool MoveFolder(string oldPath, string newPath)
    {
        try
        {
            Directory.Move(oldPath, newPath);
            return true;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 复制文件夹
    /// </summary>
    public static bool CopyFolder(string source, string destination)
    {
        try
        {
            String[] files;
            if (destination[destination.Length - 1] != Path.DirectorySeparatorChar) destination += Path.DirectorySeparatorChar;
            if (!Directory.Exists(destination)) Directory.CreateDirectory(destination);
            files = Directory.GetFileSystemEntries(source);
            foreach (string element in files)
            {
                if (Directory.Exists(element))
                    CopyFolder(element, destination + Path.GetFileName(element));
                else
                    File.Copy(element, destination + Path.GetFileName(element), true);
            }
            return true;
        }
        catch
        {
            return false;
        }
    }
    #endregion

    #region 检测文件
    /// <summary>
    /// 判断是否为安全文件名
    /// </summary>
    /// <param name="str">文件名</param>
    public static bool IsSafeName(string strExtension)
    {
        strExtension = strExtension.ToLower();
        if (strExtension.LastIndexOf(".") >= 0)
        {
            strExtension = strExtension.Substring(strExtension.LastIndexOf("."));
        }
        else
        {
            strExtension = ".txt";
        }
        string[] arrExtension = { ".htm", ".html", ".txt", ".js", ".css", ".xml", ".sitemap", ".jpg", ".gif", ".png", ".rar", ".zip" };
        for (int i = 0; i < arrExtension.Length; i++)
        {
            if (strExtension.Equals(arrExtension[i]))
            {
                return true;
            }
        }
        return false;
    }

    /// <summary>
    ///  判断是否为不安全文件名
    /// </summary>
    /// <param name="str">文件名、文件夹名</param>
    public static bool IsUnsafeName(string strExtension)
    {
        strExtension = strExtension.ToLower();
        if (strExtension.LastIndexOf(".") >= 0) 
        {
            strExtension = strExtension.Substring(strExtension.LastIndexOf("."));
        }
        else
        {
            strExtension = ".txt";
        }
        string[] arrExtension = { ".", ".asp", ".aspx", ".cs", ".net", ".dll", ".config", ".ascx", ".master", ".asmx", ".asax", ".cd", ".browser", ".rpt", ".ashx", ".xsd", ".mdf", ".resx", ".xsd" };
        for (int i = 0; i < arrExtension.Length; i++)
        {
            if (strExtension.Equals(arrExtension[i]))
            {
                return true;
            }
        }
        return false;
    }

    /// <summary>
    ///  判断是否为可编辑文件
    /// </summary>
    /// <param name="str">文件名、文件夹名</param>
    public static bool IsCanEdit(string strExtension)
    {
        strExtension = strExtension.ToLower();

        if (strExtension.LastIndexOf(".") >= 0)
        {
            strExtension = strExtension.Substring(strExtension.LastIndexOf("."));
        }
        else
        {
            strExtension = ".txt";
        }
        string[] arrExtension = { ".htm", ".html", ".txt", ".js", ".css", ".xml", ".sitemap" };
        for (int i = 0; i < arrExtension.Length; i++)
        {
            if (strExtension.Equals(arrExtension[i]))
            {
                return true;
            }
        }
        return false;
    }
    #endregion
}

转载于:https://www.cnblogs.com/mynameltg/p/4043461.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
文件管理系统是一种用于管理和组织计算机中的文件的软件系统。它允许用户通过创建、修改、删除和查找文件,有效地管理和利用计算机硬盘中的存储空间。 在Java中,我们可以使用面向对象的编程方法来实现一个文件管理系统。以下是一个简单的文件管理系统的Java源代码示例: ```java import java.util.ArrayList; import java.util.List; class File { private String name; private String extension; private int size; public File(String name, String extension, int size) { this.name = name; this.extension = extension; this.size = size; } public String getName() { return name; } public String getExtension() { return extension; } public int getSize() { return size; } public String toString() { return name + "." + extension + ", " + size + " bytes"; } } class FileManager { List<File> files; public FileManager() { files = new ArrayList<>(); } public void addFile(File file) { files.add(file); } public void deleteFile(String name) { for (File file : files) { if (file.getName().equals(name)) { files.remove(file); break; } } } public List<File> searchFiles(String keyword) { List<File> searchResults = new ArrayList<>(); for (File file : files) { if (file.getName().contains(keyword) || file.getExtension().contains(keyword)) { searchResults.add(file); } } return searchResults; } public void printFiles() { for (File file : files) { System.out.println(file); } } } public class Main { public static void main(String[] args) { FileManager fileManager = new FileManager(); fileManager.addFile(new File("document", "txt", 1024)); fileManager.addFile(new File("image", "jpg", 2048)); fileManager.addFile(new File("presentation", "ppt", 4096)); fileManager.printFiles(); fileManager.deleteFile("image"); List<File> searchResults = fileManager.searchFiles("doc"); for (File file : searchResults) { System.out.println(file); } } } ``` 以上代码演示了一个简单的文件管理系统。它使用`File`来表示文件,其中包含文件的名称、扩展名和大小。`FileManager`则提供了一些常见的文件管理功能,如添加文件、删除文件和按关键字搜索文件。在`Main`中,我们创建了一个`FileManager`对象,并使用其方法展示了如何使用该系统进行文件管理的基本操作。 当你运行这段代码时,你将看到文件被添加到文件管理系统中,并能够执行一些操作,如显示所有文件、删除文件以及按关键字搜索文件。 这只是一个基本的文件管理系统示例,你可以根据自己的需求进行扩展和定制。希望这个简单的Java源码能帮助你理解文件管理系统的实现方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值