Файловый менеджер си шарп

Разработка файлового менеджера на языке объектно-ориентированного языка программирования C#

Целью курсового проекта является разработка файлового менеджера на языке объектно-ориентированного языка программирования C#.

Актуальность использования файлового менеджера состоит в том, что зачастую крайне сложно найти нужный файл на компьютере даже при условии наличия поиска. Многие пользователи даже не знают о существовании файловых менеджеров, кроме как стандартного проводника операционной системы, но, тем не менее не малый процент пользователей используют файловые менеджеры, такие как, например, Total Commander.

Учитывая все вышесказанное, можно сделать вывод, что разработка универсального файлового менеджера с интуитивно понятным интерфейсом, небольшим объемом занимаемым на дисковом пространстве, не требующего установки и дополнительных ресурсов является очень актуальной.

 Сформировать пользовательский интерфейс;

 Разработать алгоритм получения информации о файлах и каталогах жесткого диска;

 Реализация процесса работы файлового менеджера;

 Тестирование продукта на корректность полученного результата.

В настоящее время существует огромное множество реализаций файловых менеджеров, начиная от совсем простых и свободно распространяемых, до распространенных на мировом уровне платных лицензионных продуктов. Как правило, файловый менеджер имеет примитивный интуитивно понятный интерфейс, например, самый распространенный файловый менеджер Total Commander включает в себя выделение и подсветка файлов на панели по имени, расширению, дате и времени создания файла и по многим другим условиям, расширяемым плагинами, и расширенный поиск файлов, вкладочный интерфейс, настраиваемые меню и панели инструментов с кнопками для запуска внешних программ или внутренних команд меню.

Читайте также:  Request post method python

Язык C# — объектно-ориентированный язык программирования. Разработан в 1998—2001 годах группой инженеров под руководством Андерса Хейлсберга в компании Microsoft как язык разработки приложений для платформы Microsoft .NET Framework и впоследствии был стандартизирован как ECMA-334 и ISO/IEC 23270.

C# относится к семье языков с C-подобным синтаксисом, из них его синтаксис наиболее близок к C++ и Java. Язык имеет статическую типизацию, поддерживает полиморфизм, перегрузку операторов (в том числе операторов явного и неявного приведения типа), делегаты, атрибуты, события, свойства, обобщённые типы и методы, итераторы, анонимные функции с поддержкой замыканий, LINQ, исключения, комментарии в формате XML.

Переняв многое от своих предшественников — языков C++, Pascal, Модула, Smalltalk и, в особенности, Java — С#, опираясь на практику их использования, исключает некоторые модели, зарекомендовавшие себя как проблематичные при разработке программных систем, например, C# в отличие от C++ не поддерживает множественное наследование классов (между тем допускается множественное наследование интерфейсов).

1 Анализ предметной области

1.1 Обзор существующих решений

В настоящее время существует огромное множество реализаций файловых менеджеров, начиная от совсем простых и свободно распространяемых, до распространенных на мировом уровне платных лицензионных продуктов. Как правило, файловый менеджер имеет примитивный интуитивно понятный интерфейс, например, самый распространенный файловый менеджер Total Commander включает в себя выделение и подсветку файлов на панели по имени, расширению, дате и времени создания файла и по многим другим условиям, расширяемым плагинами, и расширенный поиск файлов, вкладочный интерфейс, настраиваемые меню и панели инструментов с кнопками для запуска внешних программ или внутренних команд меню.

Файловый менеджер — это программа,

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Курсовая работа курса «Введение в C#»

lordroads/ConsoleFileManager

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

GeekBrains student of the course «Introduction to C#»

Консольный файловый менеджер начального уровня, который охватывает минимальный набор функций управления файлами.

C# Versions & Official Support

  • Имеется конфигурационный файл в корневом каталоге программы «config.json», в конфигурационном файле возможна настройка вывода количества элементов на страницу, так же там указана текущая директория и текущая выбранная страница.
  • При выходе из программы сохраняется текущий прогресс.
  • Так же при запуске программы, через командную строку, возможно передавать команды в качестве аргументов.
 [COMMANDS] /--------------------------------------------------------------------------/ VIEW (V) - Показывает выбранный каталог по странично с первой страницы. Путь содержащий пробелы необходимо заключить в ковычки. Есть дополнительный аргумент "r", используется для принудительной загрузки информации. Примеры: view "C:\Directory Name" r view C:\DirectoryName v C:\DirectoryName PAGE (P) - Переходит на указыную страницу каталога. Примеры: page 1 p 1 FILEINFO (FI) - Показывает информацию о запрашиваемом файле. Путь содержащий пробелы необходимо заключить в ковычки. Примеры: fileInfo "C:\Directory Name\file.txt" fileinfo C:\DirectoryName\file.txt fi C:\Directory Name\file.txt COPY (C) - Копирование. Может копировать файлы и каталоги с файлами. Путь содержащий пробелы необходимо заключить в ковычки. Для копирования необходимо указать: путь до файла или каталога и путь каталога куда будет производится копирование. Примеры: copy "C:\Directory Name\file.txt" "C:\New Directory Name" copy C:\DirectoryName "C:\New Directory Name" c C:\DirectoryName\file.txt C:\NewDirectoryName DELETE (D) - Удаление. Удаляет файл или каталог с файлами. Путь содержащий пробелы необходимо заключить в ковычки. Примеры: delete "C:\Directory Name\file.txt" delete C:\DirectoryName d "C:\Directory Name\file.txt" QUIT (Q) - Выход из программы. Примеры: quit exit q 

Источник

How to Build a Simple File Manager App in Windows Forms

Follow this step-by-step guide to build your own basic file manager with a minimum of fuss.

Files and folders on a bookshelf

Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.

It can be very beneficial to re-create common apps when learning about Windows Forms. Doing so can also help reinforce your basic understanding of programming. One example of an app you can build is a basic file manager.

The file manager app should consist of quick links to common Windows folders (Desktop, My Documents, Pictures, Music, and Videos). It should also have the ability to navigate up and down directories.

How to Add UI Elements Onto the Canvas

First, create a new Windows Form application in Visual Studio. Once completed, you can start adding UI elements for the file manager onto the canvas.

  1. With the canvas opened, search for a Button UI element using the Toolbox.
  2. Drag and drop five buttons to represent the quick links that are available on a Windows computer. These will represent the Desktop, My Documents, Pictures, Music, and Videos folders.

Adding five buttons to a WinForms canvas using the toolbox

Button Name Property Text Property
1 button_Desktop Desktop
2 button_Documents My Documents
3 button_Pictures Pictures
4 button_Music Music
5 button_Videos Videos

A button highlighted to show the Text attribute of one of the buttons with the value My Documents

A new panel on a WinForms canvas with the name panel_FilesList

How to Get the Current File Path

When you click on a button (for example, Desktop), the list of folders and files that are on the Desktop should display in the panel. To do this, you can get the file path of the folder you have clicked on, i.e., “C:\Users\User\Desktop”.

Write the logic for this in the code-behind C# file for the form. If you are unfamiliar with C# classes, you can learn more about classes in C#.

    Double-click on each of the buttons on the UI. This will generate click event functions for each button inside the C# file for the form. These functions will run when you click the associated button.

private void button_Desktop_Click(object sender, EventArgs e)
>

private void button_Documents_Click(object sender, EventArgs e)
>

private void button_Pictures_Click(object sender, EventArgs e)
>

private void button_Music_Click(object sender, EventArgs e)
>

private void button_Videos_Click(object sender, EventArgs e)
>
public Form1()
InitializeComponent();
DisplayFiles(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
>

private void button_Desktop_Click(object sender, EventArgs e)
DisplayFiles(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
>

private void button_Documents_Click(object sender, EventArgs e)
DisplayFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
>

private void button_Pictures_Click(object sender, EventArgs e)
DisplayFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));
>

private void button_Music_Click(object sender, EventArgs e)
DisplayFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyMusic));
>

private void button_Videos_Click(object sender, EventArgs e)
DisplayFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos));
>

How to Render the Files for the Selected Directory

Display a list of files depending on the Desktop, My Documents, Pictures, Music, or Videos button you click on.

    Import the System.IO namespace at the top of the file.

private void DisplayFiles(string filePath)
// Code to display the files and folders inside the directory
>
string[] filesList = Directory.GetDirectories(filePath).Concat(Directory.GetFiles(filePath)).ToArray(); 
panel_FilesList.Controls.Clear(); 
currentLocation = filePath; 
for (int i = 0; i < filesList.Length-1; i++)
bool isHidden = ((File.GetAttributes(filesList[i]) & FileAttributes.Hidden) == FileAttributes.Hidden);

if (!isHidden)
// Get the name of the file from the path
var startOfName = filesList[i].LastIndexOf("\\");
var fileName = filesList[i].Substring(startOfName + 1, filesList[i].Length - (startOfName + 1));

// Display the file or folder as a button
Button newButton = new Button();
newButton.Text = fileName;
newButton.Name = filesList[i];
newButton.Location = new Point(70, 70);
newButton.Size = new Size(800, 100);
newButton.TextAlign = ContentAlignment.MiddleLeft;
newButton.Padding = new Padding(24, 0, 0, 0);
panel_FilesList.Controls.Add(newButton);
>
>

Green button at the top of the Visual Studio project

List of files and directories in the My Documents folder at runtime

List of files and directories in the Videos folder at runtime

How to Navigate Up and Down Directories

Modify the code so that when you click on a folder displayed in the list, you will move down a directory. You can also create a back button to move back up to the previous folder.

    To move down a directory, create a new function called button_Click_Open(). If the user clicks on a directory in the list, the program will call the DisplayFiles() function to display the files inside that directory. If the user clicks on a file instead, the program will open the file.

private void button_Click_Open(object sender, EventArgs e)
Button button = (Button)sender;
string filePath = button.Name;

try
// If a directory clicked, reload list of files in new directory
DisplayFiles(filePath);
>
catch (Exception ex)
// If file clicked, open the file
var process = new System.Diagnostics.Process();
process.StartInfo = new System.Diagnostics.ProcessStartInfo() < UseShellExecute = true, FileName = filePath >;
process.Start();
>
>
newButton.Click += button_Click_Open;

New back button dragged onto the canvas via the toolbox

Back button renamed on the canvas

private void back_Click(object sender, EventArgs e)
>
var previousFolder = this.currentLocation.Substring(0, this.currentLocation.LastIndexOf("\\"));
DisplayFiles(previousFolder);

List of files and directories for the Pictures folder at runtime

Files and directories list after navigating down a folder

List of files and directories for the Pictures folder at runtime

Creating Desktop Apps Using Windows Forms

A file manager is a simple app that you can build when learning how to create a Windows Form application. You can use the Toolbox to drag and drop a panel onto the canvas, along with various other buttons.

Now that your app has the main functionality, feel free to modify the button properties to improve the File Manager’s design.

Discover some of the other beginner apps that you can create when learning about Windows Forms applications.

Shay loves learning new things through personal projects. Outside coding, Shay also loves gaming and playing the piano.

Источник

Оцените статью