Главная страница
Навигация по странице:

  • AttributeForm.cs

  • FileAndFolderMonitorForm.cs

  • MainForm.cs

  • Создание файлового менеджера с возможностью установки атрибутов файла в среде MS Visual C#. Курсовая Никиты. Создание файлового менеджера с возможностью установки


    Скачать 289.67 Kb.
    НазваниеСоздание файлового менеджера с возможностью установки
    АнкорСоздание файлового менеджера с возможностью установки атрибутов файла в среде MS Visual C
    Дата27.12.2021
    Размер289.67 Kb.
    Формат файлаdocx
    Имя файлаКурсовая Никиты.docx
    ТипКурсовая
    #319821
    страница5 из 6
    1   2   3   4   5   6

    Приложение


    AboutForm.cs:

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Linq;

    using System.Text;

    using System.Windows.Forms;
    namespace MyFileManager

    {

    public partial class AboutForm : Form

    {

    public AboutForm()

    {

    InitializeComponent();

    }


    private void btnConfirm_Click(object sender, EventArgs e)

    {

    this.Close();

    }
    }

    }
    AttributeForm.cs:

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Linq;

    using System.Text;

    using System.Windows.Forms;

    using System.IO;
    namespace MyFileManager

    {

    public partial class AttributeForm : Form

    {

    public AttributeForm(string filePath)

    {

    InitializeComponent();


    InitDisplay(filePath);

    }

    private void btnConfirm_Click(object sender, EventArgs e)

    {

    this.Close();

    }

    private void InitDisplay(string filePath)

    {

    if (File.Exists(filePath))

    {

    FileInfo fileInfo = new FileInfo(filePath);
    txtFileName.Text = fileInfo.Name;

    txtFileType.Text = fileInfo.Extension;

    txtFileLocation.Text = (fileInfo.DirectoryName != null) ? fileInfo.DirectoryName : null;

    txtFileSize.Text = ShowFileSize(fileInfo.Length);

    txtFileCreateTime.Text = fileInfo.CreationTime.ToString();

    txtFileModifyTime.Text = fileInfo.LastWriteTime.ToString();

    txtFileAccessTime.Text = fileInfo.LastAccessTime.ToString();

    }

    else if (Directory.Exists(filePath))

    {

    DirectoryInfo directoryInfo = new DirectoryInfo(filePath);
    txtFileName.Text = directoryInfo.Name;

    txtFileType.Text = "Папка";

    txtFileLocation.Text = (directoryInfo.Parent != null) ? directoryInfo.Parent.FullName : null;

    txtFileSize.Text = ShowFileSize(GetDirectoryLength(filePath));

    txtFileCreateTime.Text = directoryInfo.CreationTime.ToString();

    txtFileModifyTime.Text = directoryInfo.LastWriteTime.ToString();

    txtFileAccessTime.Text = directoryInfo.LastAccessTime.ToString();

    }

    }

    private long GetDirectoryLength(string dirPath)

    {

    long length = 0;

    DirectoryInfo directoryInfo = new DirectoryInfo(dirPath);


    FileInfo[] fileInfos = directoryInfo.GetFiles();

    if (fileInfos.Length > 0)

    {

    foreach (FileInfo fileInfo in fileInfos)

    {

    length += fileInfo.Length;

    }

    }


    DirectoryInfo[] directoryInfos = directoryInfo.GetDirectories();

    if(directoryInfos.Length > 0)

    {

    foreach(DirectoryInfo dirInfo in directoryInfos)

    {

    length += GetDirectoryLength(dirInfo.FullName);

    }

    }
    return length;

    }

    public static string ShowFileSize(long fileSize)

    {

    string fileSizeStr = "";
    if (fileSize < 1024)

    {

    fileSizeStr = fileSize + " байт";

    }

    else if (fileSize >= 1024 && fileSize < 1024 * 1024)

    {

    fileSizeStr = Math.Round(fileSize * 1.0 / 1024, 2, MidpointRounding.AwayFromZero) + " KB(" + fileSize + "байт)";

    }

    else if (fileSize >= 1024 * 1024 && fileSize < 1024 * 1024 * 1024)

    {

    fileSizeStr = Math.Round(fileSize * 1.0 / (1024 * 1024), 2, MidpointRounding.AwayFromZero) + " MB(" + fileSize + "байт)";

    }

    else if (fileSize >= 1024 * 1024 * 1024)

    {

    fileSizeStr = Math.Round(fileSize * 1.0 / (1024 * 1024 * 1024), 2, MidpointRounding.AwayFromZero) + " GB(" + fileSize + "байт)";

    }
    return fileSizeStr;

    }
    }

    }
    FileAndFolderMonitorForm.cs:

    using System;

    using System.Drawing;

    using System.IO;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using Microsoft.Win32;

    using System.Runtime.InteropServices;
    namespace MyFileManager

    {

    class GetSystemIcon

    {

    public static Icon GetIconByFileName(string fileName)

    {

    if (fileName == null || fileName.Equals(string.Empty)) return null;

    if (!File.Exists(fileName)) return null;
    SHFILEINFO shinfo = new SHFILEINFO();

    Win32.SHGetFileInfo(fileName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_LARGEICON);

    System.Drawing.Icon myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);

    return myIcon;

    }


    public static Icon GetIconByFileType(string fileType, bool isLarge)

    {

    if (fileType == null || fileType.Equals(string.Empty)) return null;
    RegistryKey regVersion = null;

    string regFileType = null;

    string regIconString = null;

    string systemDirectory = Environment.SystemDirectory + "\\";
    if (fileType[0] == '.')

    {

    regVersion = Registry.ClassesRoot.OpenSubKey(fileType, true);

    if (regVersion != null)

    {

    regFileType = regVersion.GetValue("") as string;

    regVersion.Close();

    regVersion = Registry.ClassesRoot.OpenSubKey(regFileType + @"\DefaultIcon", true);

    if (regVersion != null)

    {

    regIconString = regVersion.GetValue("") as string;

    regVersion.Close();

    }

    }

    if (regIconString == null)

    {

    regIconString = systemDirectory + "shell32.dll,0";

    }

    }

    else

    {

    regIconString = systemDirectory + "shell32.dll,3";

    }

    string[] fileIcon = regIconString.Split(new char[] { ',' });

    if (fileIcon.Length != 2)

    {

    fileIcon = new string[] { systemDirectory + "shell32.dll", "2" };

    }

    Icon resultIcon = null;

    try

    {

    int[] phiconLarge = new int[1];

    int[] phiconSmall = new int[1];

    uint count = Win32.ExtractIconEx(fileIcon[0], Int32.Parse(fileIcon[1]), phiconLarge, phiconSmall, 1);

    IntPtr IconHnd = new IntPtr(isLarge ? phiconLarge[0] : phiconSmall[0]);

    resultIcon = Icon.FromHandle(IconHnd);

    }

    catch { }

    return resultIcon;

    }

    }
    [StructLayout(LayoutKind.Sequential)]

    public struct SHFILEINFO

    {

    public IntPtr hIcon;

    public IntPtr iIcon;

    public uint dwAttributes;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]

    public string szDisplayName;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]

    public string szTypeName;

    };

    class Win32

    {

    public const uint SHGFI_ICON = 0x100;

    public const uint SHGFI_LARGEICON = 0x0;

    public const uint SHGFI_SMALLICON = 0x1;
    [DllImport("shell32.dll")]

    public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);

    [DllImport("shell32.dll")]

    public static extern uint ExtractIconEx(string lpszFile, int nIconIndex, int[] phiconLarge, int[] phiconSmall, uint nIcons);
    }

    }
    MainForm.cs:

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Linq;

    using System.Text;

    using System.Windows.Forms;

    using System.IO;

    using System.Diagnostics;

    using Microsoft.VisualBasic.Devices;

    using System.Threading;

    using System.Security.AccessControl;
    namespace MyFileManager

    {

    public partial class MainForm : Form

    {

    private string curFilePath = "";
    private TreeNode curSelectedNode = null;
    private bool isMove = false;
    private string[] copyFilesSourcePaths = new string[200];
    private DoublyLinkedListNode firstPathNode = new DoublyLinkedListNode();
    private DoublyLinkedListNode curPathNode = null;
    private string fileName;
    private bool isInitializeTvwDirectory = true;
    public MainForm()

    {

    InitializeComponent();

    }


    private void MainForm_Load(object sender, EventArgs e)

    {

    InitViewChecks();
    InitDisplay();

    }
    private void MainForm_Resize(object sender, EventArgs e)

    {

    tscboAddress.Width = this.Width - 290;

    }
    private void MainForm_SizeChanged(object sender, EventArgs e)

    {

    tscboAddress.Width = this.Width - 290;

    }

    private void tsmiNewFolder_Click(object sender, EventArgs e)

    {

    CreateFolder();

    }
    private void tsmiNewFile_Click(object sender, EventArgs e)

    {

    CreateFile();

    }
    private void tsmiPrivilege_Click(object sender, EventArgs e)

    {

    ShowPrivilegeForm();

    }
    private void tsmiProperties_Click(object sender, EventArgs e)

    {

    ShowAttributeForm();

    }
    private void tsmiCopy_Click(object sender, EventArgs e)

    {

    CopyFiles();

    }
    private void tsmiPaste_Click(object sender, EventArgs e)

    {

    PasteFiles();

    }
    private void tsmiCut_Click(object sender, EventArgs e)

    {

    CutFiles();

    }
    private void tsmiDelete_Click(object sender, EventArgs e)

    {

    DeleteFiles();

    }
    private void tsmiToolbar_Click(object sender, EventArgs e)

    {

    tsMain.Visible = !tsMain.Visible;
    tsmiToolbar.Checked = !tsmiToolbar.Checked;

    }
    private void tsmiStatusbar_Click(object sender, EventArgs e)

    {

    ssFooter.Visible = !ssFooter.Visible;
    tsmiStatusbar.Checked = !tsmiStatusbar.Checked;

    }
    private void tsmiBigIcon_Click(object sender, EventArgs e)

    {

    ResetViewChecks();

    tsmiBigIcon.Checked = true;

    tsmiBigIcon1.Checked = true;

    lvwFiles.View = View.LargeIcon;

    }
    private void tsmiSmallIcon_Click(object sender, EventArgs e)

    {

    ResetViewChecks();

    tsmiSmallIcon.Checked = true;

    tsmiSmallIcon1.Checked = true;

    lvwFiles.View = View.SmallIcon;

    }
    private void tsmiList_Click(object sender, EventArgs e)

    {

    ResetViewChecks();

    tsmiList.Checked = true;

    tsmiList1.Checked = true;

    lvwFiles.View = View.List;

    }
    private void tsmiDetailedInfo_Click(object sender, EventArgs e)

    {

    ResetViewChecks();

    tsmiDetailedInfo.Checked = true;

    tsmiDetailedInfo1.Checked = true;

    lvwFiles.View = View.Details;

    }
    private void tsmiRefresh_Click(object sender, EventArgs e)

    {

    ShowFilesList(curFilePath, false);

    }

    private void tsmiProcessThread_Click(object sender, EventArgs e)

    {

    ProcessForm processForm = new ProcessForm();

    processForm.Show();

    }
    private void tsmiMonitor_Click(object sender, EventArgs e)

    {

    FileAndFolderMonitorForm monitorForm = new FileAndFolderMonitorForm();

    monitorForm.Show();

    }

    private void tsmiAbout_Click(object sender, EventArgs e)

    {

    AboutForm aboutForm = new AboutForm();

    aboutForm.Show();

    }
    private void tsbtnBack_Click(object sender, EventArgs e)

    {

    if (curPathNode != firstPathNode)

    {

    curPathNode = curPathNode.PreNode;

    string prePath = curPathNode.Path;
    ShowFilesList(prePath, false);
    tsbtnAdvance.Enabled = true;

    }

    else

    {

    tsbtnBack.Enabled = false;

    }

    }
    private void tsbtnAdvance_Click(object sender, EventArgs e)

    {

    if (curPathNode.NextNode != null)

    {

    curPathNode = curPathNode.NextNode;

    string nextPath = curPathNode.Path;
    ShowFilesList(nextPath, false);
    tsbtnBack.Enabled = true;

    }

    else

    {

    tsbtnAdvance.Enabled = false;

    }

    }
    private void tsbtnUpArrow_Click(object sender, EventArgs e)

    {

    if (curFilePath == "")

    {

    return;

    }
    DirectoryInfo directoryInfo = new DirectoryInfo(curFilePath);
    if (directoryInfo.Parent != null)

    {

    ShowFilesList(directoryInfo.Parent.FullName, true);

    }

    else

    {

    return;

    }

    }

    private void tscboAddress_KeyDown(object sender, KeyEventArgs e)

    {

    if (e.KeyCode == Keys.Enter)

    {

    string newPath = tscboAddress.Text;
    if (newPath == "")

    {

    return;

    }

    else if (!Directory.Exists(newPath))

    {

    return;

    }
    ShowFilesList(newPath, true);

    }

    }

    private void tscboSearch_Enter(object sender, EventArgs e)

    {

    tscboSearch.Text = "";

    }
    private void tscboSearch_Leave(object sender, EventArgs e)

    {

    tscboSearch.Text = "Поиск";

    }
    private void tscboSearch_KeyDown(object sender, KeyEventArgs e)

    {

    if (e.KeyCode == Keys.Enter)

    {

    string fileName = tscboSearch.Text;
    if (string.IsNullOrEmpty(fileName))

    {

    return;

    }
    SearchWithMultiThread(curFilePath, fileName);

    }

    }
    private void cmsMain_Opening(object sender, CancelEventArgs e)

    {

    Point curPoint = lvwFiles.PointToClient(Cursor.Position);
    ListViewItem item = lvwFiles.GetItemAt(curPoint.X, curPoint.Y);
    if (item != null)

    {

    tsmiOpen.Visible = true;

    tsmiView1.Visible = false;

    tsmiRefresh1.Visible = false;

    tsmiCopy1.Visible = true;

    tsmiPaste1.Visible = false;

    tsmiCut1.Visible = true;

    tsmiDelete1.Visible = true;

    tsmiRename.Visible = true;

    tsmiNewFolder1.Visible = false;

    tsmiNewFile1.Visible = false;

    tssLine4.Visible = false;

    }

    else

    {

    tsmiOpen.Visible = false;

    tsmiView1.Visible = true;

    tsmiRefresh1.Visible = true;

    tsmiCopy1.Visible = false;

    tsmiPaste1.Visible = true;

    tsmiCut1.Visible = false;

    tsmiDelete1.Visible = false;

    tsmiRename.Visible = false;

    tsmiNewFolder1.Visible = true;

    tsmiNewFile1.Visible = true;

    tssLine4.Visible = true;

    }

    }
    private void tsmiOpen_Click(object sender, EventArgs e)

    {

    Open();

    }
    private void tsmiRename_Click(object sender, EventArgs e)

    {

    RenameFile();

    }
    private void lvwFiles_AfterLabelEdit(object sender, LabelEditEventArgs e)

    {

    string newName = e.Label;
    ListViewItem selectedItem = lvwFiles.SelectedItems[0];
    if (string.IsNullOrEmpty(newName))

    {

    MessageBox.Show("Имя файла не может быть пустым!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
    e.CancelEdit = true;

    }

    else if (newName == null)

    {

    return;

    }

    else if (newName == selectedItem.Text)

    {

    return;

    }

    else if (!IsValidFileName(newName))

    {

    MessageBox.Show("Имя файла не может содержать ни один из следующих символов:\r\n" + "\t\\/:*?\"<>|", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
    e.CancelEdit = true;

    }

    else

    {

    Computer myComputer = new Computer();
    if (File.Exists(selectedItem.Tag.ToString()))

    {

    if (File.Exists(Path.Combine(curFilePath, newName)))

    {

    MessageBox.Show("В текущем пути есть файл с таким же именем!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
    e.CancelEdit = true;

    }

    else

    {

    myComputer.FileSystem.RenameFile(selectedItem.Tag.ToString(), newName);
    FileInfo fileInfo = new FileInfo(selectedItem.Tag.ToString());

    string parentPath = Path.GetDirectoryName(fileInfo.FullName);

    string newPath = Path.Combine(parentPath, newName);
    selectedItem.Tag = newPath;
    LoadChildNodes(curSelectedNode);

    }

    }

    else if (Directory.Exists(selectedItem.Tag.ToString()))

    {

    if (Directory.Exists(Path.Combine(curFilePath, newName)))

    {

    MessageBox.Show("В текущем пути есть папка с таким же именем!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
    e.CancelEdit = true;

    }

    else

    {

    myComputer.FileSystem.RenameDirectory(selectedItem.Tag.ToString(), newName);
    DirectoryInfo directoryInfo = new DirectoryInfo(selectedItem.Tag.ToString());

    string parentPath = directoryInfo.Parent.FullName;

    string newPath = Path.Combine(parentPath, newName);
    selectedItem.Tag = newPath;
    LoadChildNodes(curSelectedNode);

    }

    }

    }

    }

    private void lvwFiles_ItemActivate(object sender, EventArgs e)

    {

    Open();

    }

    private void tvwDirectory_AfterSelect(object sender, TreeViewEventArgs e)

    {

    if (isInitializeTvwDirectory)

    {

    curFilePath = @"Недавний визит";

    tscboAddress.Text = curFilePath;
    firstPathNode.Path = curFilePath;

    curPathNode = firstPathNode;
    curSelectedNode = e.Node;
    ShowFilesList(curFilePath, true);
    isInitializeTvwDirectory = false;

    }

    else

    {

    curSelectedNode = e.Node;

    ShowFilesList(e.Node.Tag.ToString(), true);

    }

    }
    private void tvwDirectory_BeforeExpand(object sender, TreeViewCancelEventArgs e)

    {

    LoadChildNodes(e.Node);

    }
    private void tvwDirectory_AfterExpand(object sender, TreeViewEventArgs e)

    {

    e.Node.Expand();

    }


    private class IconsIndexes

    {

    public const int FixedDrive = 0;

    public const int CDRom = 1;

    public const int RemovableDisk = 2;

    public const int Folder = 3;

    public const int RecentFiles = 4;

    }

    class DoublyLinkedListNode

    {

    public string Path { set; get; }

    public DoublyLinkedListNode PreNode { set; get; }

    public DoublyLinkedListNode NextNode { set; get; }
    }


    private void InitDisplay()

    {

    tvwDirectory.Nodes.Clear();
    TreeNode recentFilesNode = tvwDirectory.Nodes.Add("Недавний визит");

    recentFilesNode.Tag = "Недавний визит";

    recentFilesNode.ImageIndex = IconsIndexes.RecentFiles;

    recentFilesNode.SelectedImageIndex = IconsIndexes.RecentFiles;

    DriveInfo[] driveInfos = DriveInfo.GetDrives();
    foreach (DriveInfo info in driveInfos)

    {

    TreeNode driveNode = null;
    switch (info.DriveType)

    {
    case DriveType.Fixed:
    driveNode = tvwDirectory.Nodes.Add("Локальный диск (" + info.Name.Split('\\')[0] + ")");
    driveNode.Tag = info.Name;
    driveNode.ImageIndex = IconsIndexes.FixedDrive;

    driveNode.SelectedImageIndex = IconsIndexes.FixedDrive;
    break;
    case DriveType.CDRom:
    driveNode = tvwDirectory.Nodes.Add("Оптический привод (" + info.Name.Split('\\')[0] + ")");
    driveNode.Tag = info.Name;
    driveNode.ImageIndex = IconsIndexes.CDRom;

    driveNode.SelectedImageIndex = IconsIndexes.CDRom;
    break;
    case DriveType.Removable:
    driveNode = tvwDirectory.Nodes.Add("Съемный диск(" + info.Name.Split('\\')[0] + ")");
    driveNode.Tag = info.Name;
    driveNode.ImageIndex = IconsIndexes.RemovableDisk;

    driveNode.SelectedImageIndex = IconsIndexes.RemovableDisk;
    break;

    }

    }
    foreach (TreeNode node in tvwDirectory.Nodes)

    {

    LoadChildNodes(node);

    }


    }


    private void LoadChildNodes(TreeNode node)

    {

    try

    {

    node.Nodes.Clear();
    if (node.Tag.ToString() == "Недавний визит")

    {

    return;

    }

    else

    {

    DirectoryInfo directoryInfo = new DirectoryInfo(node.Tag.ToString());

    DirectoryInfo[] directoryInfos = directoryInfo.GetDirectories();
    foreach (DirectoryInfo info in directoryInfos)

    {

    TreeNode childNode = node.Nodes.Add(info.Name);
    childNode.Tag = info.FullName;
    childNode.ImageIndex = IconsIndexes.Folder;

    childNode.SelectedImageIndex = IconsIndexes.Folder;
    childNode.Nodes.Add("");

    }

    }
    }

    catch (Exception e)

    {

    MessageBox.Show(e.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    }


    public void ShowFilesList(string path, bool isRecord)

    {

    tsbtnBack.Enabled = true;
    if (isRecord)

    {

    DoublyLinkedListNode newNode = new DoublyLinkedListNode();

    newNode.Path = path;

    curPathNode.NextNode = newNode;

    newNode.PreNode = curPathNode;
    curPathNode = newNode;

    }

    lvwFiles.BeginUpdate();
    lvwFiles.Items.Clear();
    if (path == "Недавний визит")

    {

    var recentFiles = RecentFilesUtil.GetRecentFiles();
    foreach (string file in recentFiles)

    {

    if (File.Exists(file))

    {

    FileInfo fileInfo = new FileInfo(file);
    ListViewItem item = lvwFiles.Items.Add(fileInfo.Name);
    if (fileInfo.Extension == ".exe" || fileInfo.Extension == "")

    {

    Icon fileIcon = GetSystemIcon.GetIconByFileName(fileInfo.FullName);
    ilstIcons.Images.Add(fileInfo.Name, fileIcon);
    item.ImageKey = fileInfo.Name;

    }

    else

    {

    if (!ilstIcons.Images.ContainsKey(fileInfo.Extension))

    {

    Icon fileIcon = GetSystemIcon.GetIconByFileName(fileInfo.FullName);
    ilstIcons.Images.Add(fileInfo.Extension, fileIcon);

    }
    item.ImageKey = fileInfo.Extension;

    }
    item.Tag = fileInfo.FullName;

    item.SubItems.Add(fileInfo.LastWriteTime.ToString());

    item.SubItems.Add(fileInfo.Extension + "документ");

    item.SubItems.Add(AttributeForm.ShowFileSize(fileInfo.Length).Split('(')[0]);
    }

    else if (Directory.Exists(file))

    {

    DirectoryInfo dirInfo = new DirectoryInfo(file);
    ListViewItem item = lvwFiles.Items.Add(dirInfo.Name, IconsIndexes.Folder);

    item.Tag = dirInfo.FullName;

    item.SubItems.Add(dirInfo.LastWriteTime.ToString());

    item.SubItems.Add("папка");

    item.SubItems.Add("");

    }

    }

    }

    else

    {

    try

    {

    DirectoryInfo directoryInfo = new DirectoryInfo(path);

    DirectoryInfo[] directoryInfos = directoryInfo.GetDirectories();

    FileInfo[] fileInfos = directoryInfo.GetFiles();
    foreach (ListViewItem item in lvwFiles.Items)

    {

    if (item.Text.EndsWith(".exe"))

    {

    ilstIcons.Images.RemoveByKey(item.Text);

    }

    }


    foreach (DirectoryInfo dirInfo in directoryInfos)

    {

    ListViewItem item = lvwFiles.Items.Add(dirInfo.Name, IconsIndexes.Folder);

    item.Tag = dirInfo.FullName;

    item.SubItems.Add(dirInfo.LastWriteTime.ToString());

    item.SubItems.Add("папка");

    item.SubItems.Add("");

    }
    foreach (FileInfo fileInfo in fileInfos)

    {

    ListViewItem item = lvwFiles.Items.Add(fileInfo.Name);
    if (fileInfo.Extension == ".exe" || fileInfo.Extension == "")

    {

    Icon fileIcon = GetSystemIcon.GetIconByFileName(fileInfo.FullName);
    ilstIcons.Images.Add(fileInfo.Name, fileIcon);
    item.ImageKey = fileInfo.Name;

    }

    else

    {

    if (!ilstIcons.Images.ContainsKey(fileInfo.Extension))

    {

    Icon fileIcon = GetSystemIcon.GetIconByFileName(fileInfo.FullName);
    ilstIcons.Images.Add(fileInfo.Extension, fileIcon);

    }
    item.ImageKey = fileInfo.Extension;

    }
    item.Tag = fileInfo.FullName;

    item.SubItems.Add(fileInfo.LastWriteTime.ToString());

    item.SubItems.Add(fileInfo.Extension + "документ");

    item.SubItems.Add(AttributeForm.ShowFileSize(fileInfo.Length).Split('(')[0]);

    }
    }

    catch (Exception e)

    {

    MessageBox.Show(e.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);

    }
    }

    curFilePath = path;
    tscboAddress.Text = curFilePath;
    tsslblFilesNum.Text = lvwFiles.Items.Count + " Предметы";
    lvwFiles.EndUpdate();

    }


    private bool IsValidFileName(string fileName)

    {

    bool isValid = true;
    string errChar = "\\/:*?\"<>|";
    for (int i = 0; i < errChar.Length; i++)

    {

    if (fileName.Contains(errChar[i].ToString()))

    {

    isValid = false;

    break;

    }

    }
    return isValid;

    }


    private void ShowAttributeForm()

    {

    if (lvwFiles.SelectedItems.Count == 0)

    {
    if (curFilePath == "Недавний визит")

    {

    MessageBox.Show("Невозможно просмотреть свойства текущего пути!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);

    return;

    }
    AttributeForm attributeForm = new AttributeForm(curFilePath);
    attributeForm.Show();

    }

    else

    {

    AttributeForm attributeForm = new AttributeForm(lvwFiles.SelectedItems[0].Tag.ToString());
    attributeForm.Show();

    }

    }


    private void ShowPrivilegeForm()

    {

    if (lvwFiles.SelectedItems.Count == 0)

    {

    if (curFilePath == "Недавний визит")

    {

    MessageBox.Show("Невозможно просмотреть управление полномочиями текущего пути!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);

    return;

    }
    PrivilegeForm privilegeForm = new PrivilegeForm(curFilePath);
    privilegeForm.Show();

    }

    else

    {

    PrivilegeForm privilegeForm = new PrivilegeForm(lvwFiles.SelectedItems[0].Tag.ToString());
    privilegeForm.Show();

    }
    }


    private void CreateFolder()

    {

    if (curFilePath == "Недавний визит")

    {

    MessageBox.Show("Невозможно создать новую папку по текущему пути!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);

    return;

    }
    try

    {

    int num = 1;

    string path = Path.Combine(curFilePath, "Новая папка");

    string newFolderPath = path;
    while (Directory.Exists(newFolderPath))

    {

    newFolderPath = path + "(" + num + ")";

    num++;

    }
    Directory.CreateDirectory(newFolderPath);
    ListViewItem item = lvwFiles.Items.Add("Новая папка" + (num == 1 ? "" : "(" + (num - 1) + ")"), IconsIndexes.Folder);
    item.Tag = newFolderPath;
    LoadChildNodes(curSelectedNode);

    }

    catch (Exception e)

    {

    MessageBox.Show(e.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);

    }
    }

    private void CreateFile()

    {

    if (curFilePath == "Недавний визит")

    {

    MessageBox.Show("Невозможно создать новый файл по текущему пути!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);

    return;

    }
    NewFileForm newFileForm = new NewFileForm(curFilePath, this);

    newFileForm.Show();

    }

    private void Open()

    {

    if (lvwFiles.SelectedItems.Count > 0)

    {

    string path = lvwFiles.SelectedItems[0].Tag.ToString();
    try

    {

    if (Directory.Exists(path))

    {

    ShowFilesList(path, true);

    }
    else

    {

    Process.Start(path);

    }

    }

    catch (Exception e)

    {

    MessageBox.Show(e.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    }

    }

    private void CopyFiles()

    {

    SetCopyFilesSourcePaths();

    }


    private void PasteFiles()

    {

    if (copyFilesSourcePaths[0] == null)

    {

    return;

    }
    if (!Directory.Exists(curFilePath))

    {

    return;

    }
    if (curFilePath == "Недавний визит")

    {

    MessageBox.Show("Невозможно вставить текущий путь!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);

    return;

    }
    for (int i = 0; copyFilesSourcePaths[i] != null; i++)

    {

    if (File.Exists(copyFilesSourcePaths[i]))

    {

    MoveToOrCopyToFileBySourcePath(copyFilesSourcePaths[i]);

    }

    else if (Directory.Exists(copyFilesSourcePaths[i]))

    {

    MoveToOrCopyToDirectoryBySourcePath(copyFilesSourcePaths[i]);

    }
    }
    ShowFilesList(curFilePath, false);
    LoadChildNodes(curSelectedNode);
    copyFilesSourcePaths = new string[200];

    }


    private void CutFiles()

    {

    SetCopyFilesSourcePaths();
    isMove = true;

    }


    private void DeleteFiles()

    {

    if (lvwFiles.SelectedItems.Count > 0)

    {

    DialogResult dialogResult = MessageBox.Show("Вы уверены, что хотите его удалить?", "подтвердить удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
    if (dialogResult == DialogResult.No)

    {

    return;

    }

    else

    {

    try

    {

    foreach (ListViewItem item in lvwFiles.SelectedItems)

    {

    string path = item.Tag.ToString();
    if (File.Exists(path))

    {

    File.Delete(path);

    }

    else if (Directory.Exists(path))

    {

    Directory.Delete(path, true);

    }
    lvwFiles.Items.Remove(item);

    }
    LoadChildNodes(curSelectedNode);

    }

    catch (Exception e)

    {

    MessageBox.Show(e.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    }

    }

    }


    private void SetCopyFilesSourcePaths()

    {

    if (lvwFiles.SelectedItems.Count > 0)

    {

    int i = 0;
    foreach (ListViewItem item in lvwFiles.SelectedItems)

    {

    copyFilesSourcePaths[i++] = item.Tag.ToString();

    }
    isMove = false;

    }

    }

    private void MoveToOrCopyToFileBySourcePath(string sourcePath)

    {

    try

    {

    FileInfo fileInfo = new FileInfo(sourcePath);
    string destPath = Path.Combine(curFilePath, fileInfo.Name);
    if (destPath == sourcePath)

    {

    return;

    }
    if (isMove)

    {

    fileInfo.MoveTo(destPath);

    }

    else

    {

    fileInfo.CopyTo(destPath);

    }

    }

    catch (Exception e)

    {

    MessageBox.Show(e.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);

    }
    }


    private void CopyAndPasteDirectory(DirectoryInfo sourceDirInfo, DirectoryInfo destDirInfo)

    {

    for (DirectoryInfo dirInfo = destDirInfo.Parent; dirInfo != null; dirInfo = dirInfo.Parent)

    {

    if (dirInfo.FullName == sourceDirInfo.FullName)

    {

    MessageBox.Show("Не могу скопировать! Папка назначения - это подкаталог исходной папки.!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);

    return;

    }

    }
    if (!Directory.Exists(destDirInfo.FullName))

    {

    Directory.CreateDirectory(destDirInfo.FullName);

    }
    foreach (FileInfo fileInfo in sourceDirInfo.GetFiles())

    {

    fileInfo.CopyTo(Path.Combine(destDirInfo.FullName, fileInfo.Name));

    }
    foreach (DirectoryInfo sourceSubDirInfo in sourceDirInfo.GetDirectories())

    {

    DirectoryInfo destSubDirInfo = destDirInfo.CreateSubdirectory(sourceSubDirInfo.Name);

    CopyAndPasteDirectory(sourceSubDirInfo, destSubDirInfo);

    }
    }


    private void MoveToOrCopyToDirectoryBySourcePath(string sourcePath)

    {

    try

    {

    DirectoryInfo sourceDirectoryInfo = new DirectoryInfo(sourcePath);
    string destPath = Path.Combine(curFilePath, sourceDirectoryInfo.Name);
    if (destPath == sourcePath)

    {

    return;

    }
    if (isMove)

    {
    CopyAndPasteDirectory(sourceDirectoryInfo, new DirectoryInfo(destPath));
    Directory.Delete(sourcePath, true);
    }

    else

    {

    CopyAndPasteDirectory(sourceDirectoryInfo, new DirectoryInfo(destPath));

    }

    }

    catch (Exception e)

    {

    MessageBox.Show(e.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

    }
    private void RenameFile()

    {

    if (lvwFiles.SelectedItems.Count > 0)

    {

    lvwFiles.SelectedItems[0].BeginEdit();

    }

    }


    private void InitViewChecks()

    {

    tsmiDetailedInfo.Checked = true;

    tsmiDetailedInfo1.Checked = true;

    }


    private void ResetViewChecks()

    {

    tsmiBigIcon.Checked = false;

    tsmiSmallIcon.Checked = false;

    tsmiList.Checked = false;

    tsmiDetailedInfo.Checked = false;
    tsmiBigIcon1.Checked = false;

    tsmiSmallIcon1.Checked = false;

    tsmiList1.Checked = false;

    tsmiDetailedInfo1.Checked = false;

    }
    private void SearchWithMultiThread(string path, string fileName)

    {

    lvwFiles.Items.Clear();
    tsslblFilesNum.Text = 0 + " Предметы";
    this.fileName = fileName;
    ThreadPool.SetMaxThreads(1000, 1000);
    ThreadPool.QueueUserWorkItem(new WaitCallback(Search), path);
    }


    public void Search(Object obj)

    {

    string path = obj.ToString();
    DirectorySecurity directorySecurity = new DirectorySecurity(path, AccessControlSections.Access);
    if(!directorySecurity.AreAccessRulesProtected)

    {
    DirectoryInfo directoryInfo = new DirectoryInfo(path);
    FileInfo[] fileInfos = directoryInfo.GetFiles();
    if (fileInfos.Length > 0)

    {

    foreach (FileInfo fileInfo in fileInfos)

    {

    try

    {

    if (fileInfo.Name.Split('.')[0].Contains(fileName))

    {

    AddSearchResultItemIntoList(fileInfo.FullName, true);
    tsslblFilesNum.Text = lvwFiles.Items.Count + " Предметы";

    }

    }

    catch (Exception e)

    {

    continue;

    }

    }
    }

    DirectoryInfo[] directoryInfos = directoryInfo.GetDirectories();
    if (directoryInfos.Length > 0)

    {

    foreach (DirectoryInfo dirInfo in directoryInfos)

    {

    try

    {

    if (dirInfo.Name.Contains(fileName))

    {

    AddSearchResultItemIntoList(dirInfo.FullName, false);
    tsslblFilesNum.Text = lvwFiles.Items.Count + " Предметы";

    }

    else

    {

    ThreadPool.QueueUserWorkItem(new WaitCallback(Search), dirInfo.FullName);
    }

    }

    catch (Exception e)

    {
    }
    }

    }
    }

    }

    public void SearchWithOneThread(object obj)

    {

    string path = obj.ToString();
    DirectorySecurity directorySecurity = new DirectorySecurity(path, AccessControlSections.Access);
    if (!directorySecurity.AreAccessRulesProtected)

    {
    DirectoryInfo directoryInfo = new DirectoryInfo(path);
    FileInfo[] fileInfos = directoryInfo.GetFiles();
    DirectoryInfo[] directoryInfos = directoryInfo.GetDirectories();

    if (fileInfos.Length > 0)

    {

    foreach (FileInfo fileInfo in fileInfos)

    {

    try

    {

    if (fileInfo.Name.Split('.')[0].Contains(fileName))

    {

    AddSearchResultItemIntoList(fileInfo.FullName, true);
    tsslblFilesNum.Text = lvwFiles.Items.Count + " Предметы";

    }

    }

    catch (Exception e)

    {

    continue;

    }

    }
    }

    if (directoryInfos.Length > 0)

    {

    foreach (DirectoryInfo dirInfo in directoryInfos)

    {

    try

    {

    if (dirInfo.Name.Contains(fileName))

    {

    AddSearchResultItemIntoList(dirInfo.FullName, false);
    tsslblFilesNum.Text = lvwFiles.Items.Count + " Предметы";

    }

    else

    {

    SearchWithOneThread(dirInfo.FullName);

    }

    }

    catch (Exception e)

    {

    continue;

    }

    }

    }

    }

    }


    private void AddSearchResultItemIntoList(string fullPath, bool isFile)

    {

    if (isFile)

    {

    FileInfo fileInfo = new FileInfo(fullPath);
    ListViewItem item = lvwFiles.Items.Add(fileInfo.Name);
    if (fileInfo.Extension == ".exe" || fileInfo.Extension == "")

    {

    Icon fileIcon = GetSystemIcon.GetIconByFileName(fileInfo.FullName);
    ilstIcons.Images.Add(fileInfo.Name, fileIcon);
    item.ImageKey = fileInfo.Name;

    }

    else

    {

    if (!ilstIcons.Images.ContainsKey(fileInfo.Extension))

    {

    Icon fileIcon = GetSystemIcon.GetIconByFileName(fileInfo.FullName);
    ilstIcons.Images.Add(fileInfo.Extension, fileIcon);

    }
    item.ImageKey = fileInfo.Extension;

    }
    item.Tag = fileInfo.FullName;
    item.SubItems.Add(fileInfo.LastWriteTimeUtc.ToString());

    item.SubItems.Add(fileInfo.Extension + "文件");

    item.SubItems.Add(AttributeForm.ShowFileSize(fileInfo.Length).Split('(')[0]);

    }

    else

    {

    DirectoryInfo dirInfo = new DirectoryInfo(fullPath);
    ListViewItem item = lvwFiles.Items.Add(dirInfo.Name, IconsIndexes.Folder);

    item.Tag = dirInfo.FullName;

    item.SubItems.Add(dirInfo.LastWriteTimeUtc.ToString());

    item.SubItems.Add("папка");

    item.SubItems.Add("");

    }

    }

    }
    }
    1   2   3   4   5   6


    написать администратору сайта