Создание файлового менеджера с возможностью установки атрибутов файла в среде MS Visual C#. Курсовая Никиты. Создание файлового менеджера с возможностью установки
Скачать 289.67 Kb.
|
NewFileForm.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 NewFileForm : Form { private string curPath; private MainForm mainForm; public NewFileForm(string curPath, MainForm mainForm) { InitializeComponent(); this.curPath = curPath; this.mainForm = mainForm; } private void btnConfirm_Click(object sender, EventArgs e) { string newFileName = txtNewFileName.Text; string newFilePath = Path.Combine(curPath, newFileName); if (!IsValidFileName(newFileName)) { MessageBox.Show("Имя файла не может содержать ни один из следующих символов:\r\n" + "\t\\/:*?\"<>|", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (File.Exists(newFilePath)) { MessageBox.Show("По текущему пути существует файл с таким же именем!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { File.Create(newFilePath); mainForm.ShowFilesList(curPath, false); this.Close(); } } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } 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; } } } PrivilageForm.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.Security.AccessControl; using System.Security.Principal; namespace MyFileManager { public partial class PrivilegeForm : Form { private AuthorizationRule[] accessRulesArray = null; private string fileName; private List private List private List FileSystemRights.ReadAndExecute, FileSystemRights.ListDirectory, FileSystemRights.Read, FileSystemRights.Write }; private bool isUpdateCheckBoxes = false; private int curSelected = 0; public PrivilegeForm(string fileName) { InitializeComponent(); this.fileName = fileName; InitDisplay(fileName); } private void btnConfirm_Click(object sender, EventArgs e) { this.Close(); } private void lvwGroupOrUserName_SelectedIndexChanged(object sender, EventArgs e) { if (lvwGroupOrUserName.SelectedItems.Count > 0) { curSelected = (int)lvwGroupOrUserName.SelectedItems[0].Tag; ShowPrivilegeList(); } } private void lvwPrivilege_ItemChecked(object sender, ItemCheckedEventArgs e) { if (!isUpdateCheckBoxes) { if (e.Item.Checked) { if (File.Exists(fileName) && e.Item.Text == "Список содержимого папки") { MessageBox.Show("Тип файла не поддерживает эту операцию! После этой операции он не будет сохранен!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { isUpdateCheckBoxes = true; SetPrivilegeListChecked(privilegeFlagsList[(int)e.Item.Tag]); isUpdateCheckBoxes = false; if (File.Exists(fileName)) { AddFileSecurity(fileName, accessRulesArray[curSelected].IdentityReference.Translate(typeof(NTAccount)).ToString(), fileSystemRightsList[(int)e.Item.Tag], AccessControlType.Allow); } else if (Directory.Exists(fileName)) { AddDirectorySecurity(fileName, accessRulesArray[curSelected].IdentityReference.Translate(typeof(NTAccount)).ToString(), fileSystemRightsList[(int)e.Item.Tag], AccessControlType.Allow); } } } else { isUpdateCheckBoxes = true; SetPrivilegeListUnChecked(privilegeFlagsList[(int)e.Item.Tag]); isUpdateCheckBoxes = false; if (File.Exists(fileName)) { RemoveFileSecurity(fileName, accessRulesArray[curSelected].IdentityReference.Translate(typeof(NTAccount)).ToString(), fileSystemRightsList[(int)e.Item.Tag], AccessControlType.Allow); } else if (Directory.Exists(fileName)) { RemoveDirectorySecurity(fileName, accessRulesArray[curSelected].IdentityReference.Translate(typeof(NTAccount)).ToString(), fileSystemRightsList[(int)e.Item.Tag], AccessControlType.Allow); } } } } private void InitDisplay(string fileName) { lblObjectName.Text = fileName; AuthorizationRuleCollection tempAccessRulesCollection = null; if (File.Exists(fileName)) { FileInfo fileInfo = new FileInfo(fileName); tempAccessRulesCollection = fileInfo.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); } else if (Directory.Exists(fileName)) { DirectoryInfo dirInfo = new DirectoryInfo(fileName); tempAccessRulesCollection = dirInfo.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); } AuthorizationRule[] tempAccessRulesArray = new AuthorizationRule[tempAccessRulesCollection.Count]; tempAccessRulesCollection.CopyTo(tempAccessRulesArray, 0); accessRulesArray = UniqAccessRules(tempAccessRulesArray); lvwGroupOrUserName.Items.Clear(); for (int i = 0; i < accessRulesArray.Length; i++) { ListViewItem item = lvwGroupOrUserName.Items.Add(accessRulesArray[i].IdentityReference.Translate(typeof(NTAccount)).ToString()); item.Tag = i; item.ImageIndex = IconsIndexes.GroupOrUser; } lvwGroupOrUserName.HideSelection = false; lvwGroupOrUserName.Items[0].Selected = true; ShowPrivilegeList(); } private AuthorizationRule[] UniqAccessRules(AuthorizationRule[] accessRules) { string preAccount = ""; string nextAccout; List for (int i = 0; i < accessRules.Length; i++) { nextAccout = accessRules[i].IdentityReference.Translate(typeof(NTAccount)).ToString(); if (nextAccout != preAccount) { authorizationRulesList.Add(accessRules[i]); } preAccount = nextAccout; } return authorizationRulesList.ToArray(); } private void SetPrivilegeListChecked(string privilege) { switch (privilege) { case "FullControl": foreach (ListViewItem item in lvwPrivilege.Items) { item.Checked = true; } if (File.Exists(fileName)) { lvwPrivilege.Items[3].Checked = false; } break; case "Modify": foreach (ListViewItem item in lvwPrivilege.Items) { if (item.Text == "Исправлять" || item.Text == "Прочтите и выполните" || item.Text == "Читать" || item.Text == "Писать") { item.Checked = true; } } if (Directory.Exists(fileName)) { lvwPrivilege.Items[3].Checked = true; } break; case "ReadAndExecute": foreach (ListViewItem item in lvwPrivilege.Items) { if (item.Text == "Прочтите и выполните" || item.Text == "Читать") { item.Checked = true; } } if (Directory.Exists(fileName)) { lvwPrivilege.Items[3].Checked = true; } break; case "ListDirectory": foreach (ListViewItem item in lvwPrivilege.Items) { if (item.Text == "Список содержимого папки") { item.Checked = true; } } break; case "Read": foreach (ListViewItem item in lvwPrivilege.Items) { if (item.Text == "Читать") { item.Checked = true; } } if (Directory.Exists(fileName)) { lvwPrivilege.Items[3].Checked = true; } break; case "Write": foreach (ListViewItem item in lvwPrivilege.Items) { if (item.Text == "Писать") { item.Checked = true; } } break; } } private void SetPrivilegeListUnChecked(string privilege) { switch (privilege) { case "FullControl": foreach (ListViewItem item in lvwPrivilege.Items) { item.Checked = false; } break; case "Modify": foreach (ListViewItem item in lvwPrivilege.Items) { if (item.Text == "Исправлять" || item.Text == "Прочтите и выполните" || item.Text == "Читать" || item.Text == "Писать") { item.Checked = false; } } break; case "ReadAndExecute": foreach (ListViewItem item in lvwPrivilege.Items) { if (item.Text == "Прочтите и выполните" || item.Text == "Читать") { item.Checked = false; } } break; case "ListDirectory": foreach (ListViewItem item in lvwPrivilege.Items) { if (item.Text == "Список содержимого папки") { item.Checked = false; } } break; case "Read": foreach (ListViewItem item in lvwPrivilege.Items) { if (item.Text == "Читать") { item.Checked = false; } } break; case "Write": foreach (ListViewItem item in lvwPrivilege.Items) { if (item.Text == "Писать") { item.Checked = false; } } break; } } private void ShowPrivilegeList() { isUpdateCheckBoxes = true; lblPrivilege.Text = lvwGroupOrUserName.Items[curSelected].Text + " разрешение:"; lvwPrivilege.Items.Clear(); List for (int i = 0; i < privilegeList.Count; i++) { ListViewItem item = lvwPrivilege.Items.Add(privilegeList[i], IconsIndexes.Privilege); item.Tag = i; } for (int i = 0; i < privilegeList.Count; i++) { if (privileges.Contains(privilegeFlagsList[i])) { SetPrivilegeListChecked(privilegeFlagsList[i]); } } isUpdateCheckBoxes = false; } private void AddFileSecurity(string fileName, string account, FileSystemRights rights, AccessControlType controlType) { FileInfo fileInfo = new FileInfo(fileName); FileSecurity fileSecurity = fileInfo.GetAccessControl(); fileSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType)); fileInfo.SetAccessControl(fileSecurity); } private void RemoveFileSecurity(string fileName, string account, FileSystemRights rights, AccessControlType controlType) { FileInfo fileInfo = new FileInfo(fileName); FileSecurity fileSecurity = fileInfo.GetAccessControl(); fileSecurity.RemoveAccessRule(new FileSystemAccessRule(account, rights, controlType)); fileInfo.SetAccessControl(fileSecurity); } private void AddDirectorySecurity(string dirName, string account, FileSystemRights rights, AccessControlType controlType) { DirectoryInfo dirInfo = new DirectoryInfo(dirName); DirectorySecurity dirSecurity = dirInfo.GetAccessControl(AccessControlSections.All); dirSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType)); dirInfo.SetAccessControl(dirSecurity); } private void RemoveDirectorySecurity(string dirName, string account, FileSystemRights rights, AccessControlType controlType) { DirectoryInfo dirInfo = new DirectoryInfo(dirName); DirectorySecurity dirSecurity = dirInfo.GetAccessControl(); dirSecurity.RemoveAccessRule(new FileSystemAccessRule(account, rights, controlType)); dirInfo.SetAccessControl(dirSecurity); } class IconsIndexes { public const int GroupOrUser = 0; //组或用户 public const int Privilege = 1; //权限 } } } ProcessForm.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Security.Authentication; using System.Text; using System.Windows.Forms; namespace MyFileManager { public partial class ProcessForm : Form { public ProcessForm() { InitializeComponent(); } private void ProcessForm_Load(object sender, EventArgs e) { ShowProcesses(); } private void btnRefresh_Click(object sender, EventArgs e) { RefreshDisplay(); } private void btnFinish_Click(object sender, EventArgs e) { StopProcess(); } private void tsmiThread_Click(object sender, EventArgs e) { if (lvwProcess.SelectedItems.Count > 0) { string processName = lvwProcess.SelectedItems[0].Text; ThreadForm threadForm = new ThreadForm(processName); threadForm.Show(); } } private void ShowProcesses() { lvwProcess.Items.Clear(); Process[] processesList = Process.GetProcesses(); txtCurProcessNum.Text = processesList.Length.ToString(); try { foreach (Process process in processesList) { ListViewItem item = lvwProcess.Items.Add(process.ProcessName, IconsIndexes.Process); item.SubItems.Add(process.Id.ToString()); item.SubItems.Add(AttributeForm.ShowFileSize(process.PrivateMemorySize64).Split('(')[0]); item.SubItems.Add(AttributeForm.ShowFileSize(process.VirtualMemorySize64).Split('(')[0]); item.SubItems.Add(process.StartTime.ToLongDateString() + process.StartTime.ToLongTimeString()); item.SubItems.Add(process.BasePriority.ToString()); item.SubItems.Add(process.MainModule.FileName); } } catch(Exception e) { } } private void StopProcess() { if(lvwProcess.SelectedItems.Count > 0) { try { string processName = lvwProcess.SelectedItems[0].Text; Process process = Process.GetProcessesByName(processName)[0]; process.Kill(); RefreshDisplay(); } catch(Exception e) { MessageBox.Show("Невозможно закрыть этот процесс!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("Пожалуйста, выберите процесс!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void RefreshDisplay() { ShowProcesses(); } class IconsIndexes { public const int Process = 0; } } } RecentFilesUtil.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; //Directory 目录 using System.Reflection; //BindingFlags 枚举 namespace MyFileManager { class RecentFilesUtil { public static string GetShortcutTargetFilePath(string shortcutFilename) { var type = Type.GetTypeFromProgID("WScript.Shell"); object instance = Activator.CreateInstance(type); var result = type.InvokeMember("CreateShortCut", BindingFlags.InvokeMethod, null, instance, new object[] { shortcutFilename }); var targetFilePath = result.GetType().InvokeMember("TargetPath", BindingFlags.GetProperty, null, result, null) as string; return targetFilePath; } public static IEnumerable { var recentFolder = Environment.GetFolderPath(Environment.SpecialFolder.Recent); return from file in Directory.EnumerateFiles(recentFolder) where Path.GetExtension(file) == ".lnk" select GetShortcutTargetFilePath(file); } } } |