Thursday, July 21, 2016

Rad sa drajverima, folderima i fajlovima u C# programskom jeziku


Bez obzira da li radite sa drajverima, folderima ili fajlovima; retko će te biti u situaciji da radite samo sa folderima ili samo sa fajlovima. U većini slučajeva gde su vam potrebni fajlovi, tu su vam potrebni i drajveri i folderi. Naravno kad kažem drajveri ne mislim na drajvere datoteke za hardverske uređaje u vašim računarima, nego drajvere zovemo i alfabete koji vidite kao root node u direktorijumu kad pokrenete File Explorer ili Command Prompt. Srećom i zahvaljujući Microsoft programerima; .Net Framework vam svojim klasama itekako olakšava rad sa istim, s time da vi trebate da poznajete određene klase i metode. Jednostavno treba da poznajete rad sa klasama poput Environment, DriveInfo, Directory, DirectoryInfo, File i FileInfo. Poznavanjem ovih par klasa niste ni svesni koliki programerski posao će one obavljati za vas.


( Klase koje morate znati; Environment, DriveInfo, Directory, DirectoryInfo, File i FileInfo )  

Do sada ste verovatno primetili da smo klasu okruženja Environment već koristili skoro u svim C# primerima na ovom blogu; jednostavno smo umesto eskejp sekvence \n za prelazak u novi red koristili Environment.NewLine. Neki od mojih kolega smatraju da sam to radio radi čitljivosti koda i nije im jasno zašto ne koristim eskejp sekvence \n jer skraćuje kod; često se koristi u školama i u knjigama za C# programiranje. Istina je da uvek trebate voditi računa i o čitljivosti koda, mada treba da znate i da se prelazak u novi red na različitim operativnim sistemima ne kompajlira isto. Npr. u Windows-u je to "\r\n" (\u000D\u000A) , na iOS operativnom sistemu je to "\r" (\u000D) dok je na Unix sistemu "\n" (\u000A). Većini programera; pogotovo onih koji koriste samo Windows operativni sistem to nije ni toliko bitno, ali iz tog razloga postoji preporuka Microsoft-a da se uvek koristi Environment.NewLine umesto eskejp sekvence \n kad god je to moguće i ja jednostavno poštujem preporuku. Međutim, klasa okruženja Environment ne služi samo za tu svrhu, već takođe obezbeđuje i informacije o platformi i okruženju na kom radite. Pogledajte samo neke od propertije i metode klase Environment.
  • CurrentDirectory – properti koji omogućava set-ovanje i čitanje tekućeg direktorijuma 
  • Is64BitOperatingSistem – properti koji vraća vrednost true ukoliko koristite 64bit-ni operativni sistem
  • MachineName – properti koji prikazuje NetBIOS ime lokalnog kompjutera ili ne iz bezbednosnih razloga
  • NewLine – properti koji se koristi za prelazak u novi red
  • OSVersion – properti koji prikazuje indikator za tekući OS i verziju
  • SystemDirectory – properti koji prikazuje putanju sistemskog direktorijuma
  • GetLogicalDrives – metoda prikazuje niz imena drajvera u tekućem kompjuteru
  • Itd.
Za razliku od klase Environment, klasa Directory ne sadrži uopšte propertije, samo korisne metode za rad sa direktorijuma poput:
  • CreateDirectory – kreira direktorijume i pod direktorijume ukoliko već ne postoje
  • Delete – briše prazan direktorijum
  • Exists – proverava da li postoji navedeni direktorijum
  • GetCurrentDirectory – metoda koja vraća string tekućeg direktorijuma
  • GetDirectories – metoda koja vraća pod direktorijume u direktorijumu prema zadatom obrascu
  • Itd.
Kako se koriste navedene klase najbolje će te shvatiti njihovom praktičnom primenom. U svakom slučaju da bi ste koristili mogućnosti navedeni klasa predlažem vam da prvo uključite imenski prostor System.IO u vašem projektu.

Praktičan primer rada sa drajverima i folderima

S obzirom na klase koje nam omogućavaju jednostavan rad sa drajverima i folderima ali i mnoštvo mogućnosti; sledeći programski primer demonstrira upotrebu istih za rad sa direktorijumima koje će te itekako koristiti s vremena na vreme i u vašim projektima. Zbog mnoštva stvari koje hoćemo da nam program predstavi, za svaku mogućnost rada na direktorijumu ćemo kreirati zasebnu metodu. Program jednostavno nazovite Directories i prvo uvedite sledeće imenske prostore:

using static System.Console;

i

using System.IO;

U sledećem primeru ćemo koristiti i klase Visual Basic-a u našem C# programskom jeziku, da nam olakšaju neke stvari ali da vidite i da je to čak moguće. Dodajte sledeću referencu u vašem projektu. Otvorite Solution Explorer u vašem Microsoft Visual Studio-u, zatim u direktorijumu vašeg projekta kliknite desnim tasterom miša na direktorijum References, zatim kliknite na Add Reference i iz Assemblies – Framework čekirajte referencu na Microsoft.VisualBasic i potvrdite vaš izbor. Međutim nemojte kucati imenski prostor:

using Microsoft.VisualBasic.FileIO;
 
To radimo da nebi dolazilo do konflikta u programu. Već je bolje koristiti celu putanju imenskog prostora tamo gde nam bude trebala. Zatim krećemo izradu programa od metoda. Kad god imate mnogo različitih zadataka u jednom programu, podelite kod na metode. Za početak pravimo meni u posebnoj metodi koji će olakšati korisniku upotrebu programa ali će i vama za početak dati neku orjentaciju šta program treba sve da radi. Zato prvu metodu napravite statičnom i sa povratnom vrednošću tipa byte podataka.

  static byte DisplayMenu()
        {
            Clear();

            byte choose = 0;
                       
            WriteLine(Environment.NewLine + "\t\tD I R E C T O R I E S" + Environment.NewLine);
            WriteLine("\t\t\t 1. LIST DRIVERS" + Environment.NewLine);
            WriteLine("\t\t\t 2. THE CURRENT DIRECTORY" + Environment.NewLine);
            WriteLine("\t\t\t 3. LIST DIRECTORIES" + Environment.NewLine);
            WriteLine("\t\t\t 4. LIST ALL SPECIAL DIRECTORIES" + Environment.NewLine);
            WriteLine("\t\t\t 5. CREATE DIRECTORY" + Environment.NewLine);
            WriteLine("\t\t\t 6. RENAME DIRECTORY" + Environment.NewLine);
            WriteLine("\t\t\t 7. COPY DIRECTORY" + Environment.NewLine);
            WriteLine("\t\t\t 8. MOVE DIRECTORY" + Environment.NewLine);
            WriteLine("\t\t\t 9. DELETE DIRECTORY" + Environment.NewLine);
            WriteLine("\t\t\t10. EXIT" + Environment.NewLine);

            Write(Environment.NewLine + "\tYour choose is: ");
            bool result = Byte.TryParse(ReadLine(), out choose);

            if (!result || choose > 10 || choose < 1) DisplayMenu();

            return choose;

        }

Na osnovu predhodnog koda znamo da nam je potrebno čak 10 metoda koje će nam predstavljati meni i 9 opcija za rad sa drajverima i folderima. Svaka ova metoda je izuzetno korisna i na najjednostavniji način predstavlja svoje mogućnosti. Prva opcija u našem meniju je mogućnost da možemo da izlistamo sve drajvere u našem računaru i da na primer vidimo nazive label-a; ako računar ima naziv label-a, zatim da vidimo koliko postoji prostora u GB za svaki drajver i najvažnije koliko ima slobodnog prostora. Ukoliko imamo CD/DVD uređaje i u njima nemamo CD ili DVD dobićemo samo ispis u konzoli:

The device is not ready.

Pogledajte kod prve metode:

   static void ListDrivers()
        {
            string[] drivers = Environment.GetLogicalDrives();

            Clear();
            WriteLine("The drivers in your computer are: " + Environment.NewLine);

            foreach (string driver in drivers)
            {
                try
                {
                    WriteLine($"Driver: {driver}");

                    DriveInfo di = new DriveInfo(driver);
                    WriteLine($"Volume: {di.VolumeLabel}");
                    WriteLine($"Total Space: {di.TotalSize / 1073741824} GB");
                    WriteLine($"Free Space: {di.TotalFreeSpace / 1073741824} GB" + Environment.NewLine);

                }
                catch (Exception e)
                {
                    WriteLine(e.Message);

                }               
            }

            ReadKey();

        }

Klasa DriveInfo je nezaobilazna kad nam trebaju informacije o drajverima. S obzirom da klasa DriveInfo sadrži i propertije TotalSize i TotalFreeSpace izraženim u bajtima, na programeru je da informaciju predstavi korisniku u ovom slučaju u GB – Gigabajtima. Sledeća metoda ima za cilj da nam predstavi tekući direktorijum našeg programa i da nam pruži neke informacije o folderu gde se program nalazi.

static void CustomCurrentDirectory()
        {
            Clear();

            WriteLine("The current directory of this program is: " + Environment.NewLine);

            DirectoryInfo di = new DirectoryInfo(Environment.CurrentDirectory);
            WriteLine($"Root: {di.Root}" + Environment.NewLine);
            WriteLine($"Attributes: {di.Attributes}" + Environment.NewLine);
            WriteLine($"Name: {di.Name}" + Environment.NewLine);
            WriteLine($"Full name: {di.FullName}" + Environment.NewLine);
            WriteLine($"Creation time: {di.CreationTime}" + Environment.NewLine);
            WriteLine($"Last access time: {di.LastAccessTime}" + Environment.NewLine);
            WriteLine($"Last write time: {di.LastWriteTime}" + Environment.NewLine);

            ReadKey();

        }

Obratite pažnju na propertije klase DirectoryInfo i njihovu jednostavnu upotrebu. Klasa Environment koja nam daje tekući direktorijum može takođe i da set-uje određeni direktorijum, što nije slučaj u ovom primeru jer je nepotrebno. Takođe klasa DirectoryInfo pored korisnih propertija takođe sadrži mnoštvo korisnih metoda koje možete koristiti u vašim programima. Metodu za listing direktorijuma smo ograničili da nam prikaže samo direktorijume u direktorijumu koji je korisnik naveo.

static void ListDirectories()
        {
            Clear();
                       
            Write("Write the top path of directory for listing: ");
            string directory = ReadLine();

            try
            {
                string[] dirs = Directory.GetDirectories(directory);

                WriteLine(Environment.NewLine + $"The number of directories is {dirs.Length}.");
                WriteLine(Environment.NewLine);

                foreach (string dir in dirs)
                {
                    WriteLine(dir);

                }

            }
            catch (Exception ex)
            {
                WriteLine(Environment.NewLine + ex.Message);
               
            }

            ReadKey();

        }

Kao što vidite u ovom primeru smo koristili jednostavnu metodu sa jednim atributom GetDirectories() inače ovoj metodi možete pridružiti dodatni atribute sa opcijama pretraživanja ili ignorisanje određenih pod direktorijuma. Možda ste primetili da takođe nemate potrebe da proveravate da li direktorijum uopšte postoji, pošto struktura try catch za hvatanje izuzetaka odlično obavlja svoj posao. Međutim, možete se zapitati šta je sa specijalnim direktorijumima. Rad sa specijalnim metodama je jednostavan. Zato sledeća metoda ima za cilj da vam navede sve specijalne direktorijume i da vam pokaže punu putanju istih i koliko specijalni direktorijum postoji u vašem računaru.

static void ListAllSpecialFolders()
        {
            Clear();

            WriteLine("Special folders in your computer are: " + Environment.NewLine);

            string[] paths = Enum.GetNames(typeof(Environment.SpecialFolder));

            foreach (string path in paths)
            {
                Environment.SpecialFolder specialFolder = (Environment.SpecialFolder)Enum.Parse(
                                                           typeof(Environment.SpecialFolder), path);

                WriteLine(specialFolder + " - " + Environment.GetFolderPath(specialFolder));

            }

            ReadKey();

        }

Zahvaljujući enumeraciji ovaj samo na izgled komplikovan zadatak se obavlja sa jednostavnom petljom i par linija koda. Sledeće metoda je korisnija, njen zadatak je da kreira novi direktorijum. Ali kod nje koristimo upit koji proverava da li direktorijum postoji. Imajte samo u vidu i da bez ove dodatne provere, ukoliko direktorijum postoji neće se napraviti novi direktorijum preko postojećeg i pregaziti fajlovi. Jednostavno se neće desiti ništa, dok mi na primer u ovom slučaju hoćemo da budemo informisani ukoliko direktorijum već postoji i zato koristimo metodu Exists().

   static void CreateDirectory()
        {
            Clear();

            Write("Write the all path of directory: ");
            string directory = ReadLine();

            try
            {
                if (Directory.Exists(directory))
                {
                    WriteLine("The directory exists, already!");

                }
                else
                {
                    Directory.CreateDirectory(directory);
                    WriteLine(Environment.NewLine + "You created the directory, successfully!" + Environment.NewLine);

                }
            }
            catch (Exception ex)
            {
                WriteLine(ex.Message);
                               
            }

            ReadKey();

        }

Sledeća metoda nam služi da promenimo ime direktorijumu. Obratite pažnju da u ovom slučaju koristimo metodu RenameDirectory pravljenoj u Visual Basic programskom jeziku. Za menjanje imena direktorijuma u C# programskom jeziku ne postoji određena metoda. Tada imate mogućnost da koristite metodu Move klase Directory u C# programskom jeziku i da improvizujete ili da pozovete metodu RenameDirectory iz Visual Basic programskog jezika.

static void RenameDirectory()
        {
            Clear();

            Write("Write the all path of the directory who wish to rename: ");
            string oldDirectory = ReadLine();

            Write("Write only new name: ");
            string newName = ReadLine();

            try
            {
                if (Directory.Exists(oldDirectory))
                {
                    Microsoft.VisualBasic.FileIO.FileSystem.RenameDirectory(oldDirectory, newName);
                    WriteLine(Environment.NewLine + "You renamed the directory, successfully!" + Environment.NewLine);

                }
                else
                {
                    WriteLine("The directory not exist!");

                }

            }
            catch (Exception ex)
            {
                WriteLine(ex.Message);

            }

            ReadKey();

        }

Za kopiranje direktorijuma takođe možemo da koristimo metodu CopyDirectory iz Visual Basic programskog jezika jer u C# programskom jeziku bi ste morali napraviti izuzetno komplikovanu metodu da vam odradi tako prostu stvar. Pomisliće te da je taj Visual Basic bolji programski jezik, ali se kod nas na žalost slabo koristi.

static void CopyDirectory()
        {
            Clear();

            Write("Write the all path of directory who wish to copy: ");
            string copyDirectory = ReadLine();

            Write("Write the all path of the destination directory: ");
            string destinationDirectory = ReadLine();

            try
            {
                Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(copyDirectory, destinationDirectory,
                                             Microsoft.VisualBasic.FileIO.UIOption.AllDialogs);

                WriteLine(Environment.NewLine + "You copied the directory, successfully!" + Environment.NewLine);

            }
            catch (Exception ex)
            {
                WriteLine(ex.Message);
              
            }

            ReadKey();

        }

Sledećom metodom pomeramo celi direktorijum sa jednog direktorijuma na drugi. To nam omogućava metoda Move klase Directory. Ovu metodu koriste i za improvizaciju menjanja imena direktorijuma u C# programskom jeziku.

   static void MoveDirectory()
        {
            Clear();

            Write("Enter all the path of directory for moving: ");
            string directoryOld = ReadLine();

            Write("Enter all the path of destination directory: ");
            string directoryNew = ReadLine();

            try
            {
                Directory.Move(directoryOld, directoryNew);

                WriteLine(Environment.NewLine + "You moved the directory, successfully!" + Environment.NewLine);

            }
            catch (Exception ex)
            {
                WriteLine(ex.Message);
             
            }

            ReadKey();

        }

I zadnja metoda jednostavno briše direktorijum. Obratite pažnju da u metodi Delete klase Directory koristite i drugi parametar, tj. podešena je rekurzivna vrednost tipa boolean na true. Ukoliko drugi parametar izostavite ili podesite na false, nećete moći obrisati direktorijum ako u direktorijum sadrži bilo koji fajl u direktorijumu.  

static void DeleteDirectory()
        {
            Clear();

            Write("Enter all the path of the directory for delete: ");
            string directory = ReadLine();

            try
            {
                Directory.Delete(directory, true);
                WriteLine(Environment.NewLine + "The directory deleted, successfully!");

            }
            catch (Exception ex)
            {
                WriteLine(ex.Message);
              
            }

            ReadKey();

        }

Sad kad imamo sve neophodne metode, da bi nam radio meni koristićemo jednu do while petlju i strukturu swich case. Sad program može da odradi skoro sve operacije nad direktorijumima.

  static void Main(string[] args)
        {
            byte userInput = 0;

            do
            {
                userInput = DisplayMenu();

                switch (userInput)
                {
                    case 1:
                        ListDrivers();
                        break;

                    case 2:
                        CustomCurrentDirectory();
                        break;

                    case 3:
                        ListDirectories();
                        break;

                    case 4:
                        ListAllSpecialFolders();
                        break;

                    case 5:
                        CreatyDirectory();
                        break;

                    case 6:
                        RenameDirectory();
                        break;

                    case 7:
                        CopyDirectory();
                        break;

                    case 8:
                        MoveDirectory();
                        break;

                    case 9:
                        DeleteDirectory();
                        break;

                    default:
                        break;
                }

            } while (userInput != 10);

            WriteLine(Environment.NewLine + "Press any key to continue...");
            ReadKey();

        }

Kad pokrenemo program pojaviće nam se sledeći meni:

D I R E C T O R I E S

                         1. LIST DRIVERS

                         2. THE CURRENT DIRECTORY

                         3. LIST DIRECTORIES

                         4. LIST ALL SPECIAL DIRECTORIES

                         5. CREATE DIRECTORY

                         6. RENAME DIRECTORY

                         7. COPY DIRECTORY

                         8. MOVE DIRECTORY

                         9. DELETE DIRECTORY

                        10. EXIT


        Your choose is:

Opcija 1 omogućava da nam program prikaže sve drajvere koje imamo u računaru. Ukoliko je drajver aktivan prikazuje nam se naziv label-e ili volume drajvera i koliko imamo slobodnog prostora u gigabajtima. Za CD/DVD uređaje se prikazuje poruka da uređaji nisu aktivni ukoliko u njima nije pokrenut ni jedan CD ili DVD. Na mom računaru koji trenutno koristim to izgleda ovako:

The drivers in your computer are:

Driver: C:\
Volume:
Total Space: 930 GB
Free Space: 830 GB

Driver: D:\
The device is not ready.

Driver: E:\
The device is not ready.


Tu program nije završen već pritiskom na bilo koji taster vraćate se na meni. Opcija 2 omogućava izlistavanje tekućeg direktorijuma u kojem se nalazi program na vašem računaru.

The current directory of this program is:

Root: C:\
Attributes: Directory
Name: Debug
Full name: C:\Workshop\test\Directories\Directories\bin\Debug
Creation Time: 6/20/2016 3:52:54 PM
Last access time: 6/20/2016 6:26:25 PM
Last write time: 6/20/2016 6:26:25 PM


Opcija 3 vam omogućava da pogledate koliko i koje sve direktorijume sadrži direktorijum čiju putanju navedete.

Write the top path of directory for listing: c:\tutorials

The number of directories is 3.

c:\tutorials\HTML5 & CSS3 Fundamentals
c:\tutorials\JavaScript Fundamentals for Absolute Beginners
c:\tutorials\Unity Projects


Koji su to specijalni folderi, koje vaš računar sadrži i u kojim putanjama se nalaze će te jednostavno saznati opcijom 4 koja izlistava sve specijalne foldere u vašem računaru. Naravno, vi će te koristiti samo neke specijalne foldere u vašem radu ali zanimljivo je pogledati koje sve postoje.

Special Folders in your computer are:

Desktop - C:\Users\Manuel\Desktop
Programs - C:\Users\Manuel\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
MyDocuments - C:\Users\Manuel\Documents
MyDocuments - C:\Users\Manuel\Documents
Favorites - C:\Users\Manuel\Favorites
Startup - C:\Users\Manuel\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Recent - C:\Users\Manuel\AppData\Roaming\Microsoft\Windows\Recent
SendTo - C:\Users\Manuel\AppData\Roaming\Microsoft\Windows\SendTo
StartMenu - C:\Users\Manuel\AppData\Roaming\Microsoft\Windows\Start Menu
MyMusic - C:\Users\Manuel\Music
MyVideos - C:\Users\Manuel\Videos
DesktopDirectory - C:\Users\Manuel\Desktop
MyComputer -
NetworkShortcuts - C:\Users\Manuel\AppData\Roaming\Microsoft\Windows\Network Shortcuts
Fonts - C:\Windows\Fonts
Templates - C:\Users\Manuel\AppData\Roaming\Microsoft\Windows\Templates
CommonStartMenu - C:\ProgramData\Microsoft\Windows\Start Menu
CommonPrograms - C:\ProgramData\Microsoft\Windows\Start Menu\Programs
CommonStartup - C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
CommonDesktopDirectory - C:\Users\Public\Desktop
ApplicationData - C:\Users\Manuel\AppData\Roaming
PrinterShortcuts - C:\Users\Manuel\AppData\Roaming\Microsoft\Windows\Printer Shortcuts
LocalApplicationData - C:\Users\Manuel\AppData\Local
InternetCache - C:\Users\Manuel\AppData\Local\Microsoft\Windows\INetCache
Cookies - C:\Users\Manuel\AppData\Local\Microsoft\Windows\INetCookies
History - C:\Users\Manuel\AppData\Local\Microsoft\Windows\History
CommonApplicationData - C:\ProgramData
Windows - C:\Windows
System - C:\Windows\system32
ProgramFiles - C:\Program Files (x86)
MyPictures - C:\Users\Manuel\Pictures
UserProfile - C:\Users\Manuel
SystemX86 - C:\Windows\SysWOW64
ProgramFilesX86 - C:\Program Files (x86)
CommonProgramFiles - C:\Program Files (x86)\Common Files
CommonProgramFilesX86 - C:\Program Files (x86)\Common Files
CommonTemplates - C:\ProgramData\Microsoft\Windows\Templates
CommonDocuments - C:\Users\Public\Documents
CommonAdminTools - C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools
AdminTools - C:\Users\Manuel\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Administrative Tools
CommonMusic - C:\Users\Public\Music
CommonPictures - C:\Users\Public\Pictures
CommonVideos - C:\Users\Public\Videos
Resources - C:\Windows\resources
LocalizedResources -
CommonOemLinks -
CDBurning - C:\Users\Manuel\AppData\Local\Microsoft\Windows\Burn\Burn

Opcija 5 vam omogućava da kreirate direktorijum.

Write the all path of directory: c:\test\test1

You created the directory, successfully!


Opcija 6 vam omogućava da promenite ime direktorijuma.

Write the all path of the directory who wish to rename: c:\test\test1
Write only new name: test

You renamed the directory, successfully!


Opcija 7 vam omogućava da kopirate jedan direktorijum u drugi. Ukoliko direktorijum ne postoji u kojem hoćete da kopirate vaš direktorijum, program će ga kreirati i kopirati direktorijum sa svim fajlovima i drugim folderima u direktorijumu.

Write the all path of directory who wish to copy: c:\test\test
Write the all path of the destination directory: c:\test\test1 


You copied the directory, successfully!


Opcija 8 vam omogućava pomeranje direktorijuma sa jedne destinacije na drugu destinaciju. C# programski jezik to obavlja jednostavno.

Enter all the path of directory for moving: c:\test\test1
Enter all the path of destination directory: c:\test\test\test1

You moved the directory, successfully!


I opcija 9 vam omogućava da obrišete direktorijum. Jedino što morate navesti celu putanju direktorijuma. Do sada ste i sami mogli doći da vi celo vreme pri svakoj akciji sa direktorijuma navodite celu putanju. I u File Explorer-u; vi kad kliknete na neki folder, vaša selekcija pamti celu putanju i vi kao programer opet radite sa celim putanjama direktorijumima.

Enter all the path of the directory for delete: c:\test\test\test1

You deleted the directory, successfully!


Kako navedeni program izgleda možete pogledati i na video-u:


( C# 6.0 Tutorial - Advanced - 44. Working With Directories )

Praktičan primer rada sa fajlovima

Da bi smo prikazali mnogobrojne mogućnosti koje možete raditi sa fajlovima u C# programskom jeziku, napravićemo sličan program kao prethodni samo ćemo umesto operacija nad direktorijumima napisati metode koje obavljaju operacije nad fajlom. Što se tiče fajlova treba da shvatite da je fajl samo kolekcija sačuvanih podataka na disku ili nekom drugom uređaju i da svaki fajl ima svoje ime i svoju putanju. To su najbitniji propertiji za svaki fajl. S obzirom da u programu nema potrebe nešto posebno objašnjavati svaku metodu posebno u radu sa fajlovima poput kopiranja, pomeranja, preimenovanja ili brisanja fajla jer je kod jednostavan; pogledajte celi kod programa.

using System;
using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Files
{
    class Program
    {
        static void Main(string[] args)
        {
            byte userInput = 0;

            do
            {
                userInput = DisplayMenu();

                switch (userInput)
                {
                    case 1:
                        GetFilesFromDirectory();
                        break;

                    case 2:
                        GetInfoAboutFile();
                        break;

                    case 3:
                        RenameFile();
                        break;

                    case 4:
                        CopyFile();
                        break;

                    case 5:
                        MoveFile();
                        break;

                    case 6:
                        DeleteFile();
                        break;

                    default:
                        break;
                }


            } while (userInput != 7);

            WriteLine(Environment.NewLine + "Press any key to continue...");
            ReadKey();

        }

        static byte DisplayMenu()
        {
            Clear();

            byte choose = 0;

            WriteLine(Environment.NewLine + "\t\tF I L E S" + Environment.NewLine);
            WriteLine("\t\t\t 1. LIST ALL FILES FROM THE DIRECTORY" + Environment.NewLine);
            WriteLine("\t\t\t 2. INFO ABOUT THE FILE" + Environment.NewLine);
            WriteLine("\t\t\t 3. RENAME THE FILE" + Environment.NewLine);
            WriteLine("\t\t\t 4. COPY THE FILE" + Environment.NewLine);
            WriteLine("\t\t\t 5. MOVE THE FILE" + Environment.NewLine);
            WriteLine("\t\t\t 6. DELETE THE FILE" + Environment.NewLine);
            WriteLine("\t\t\t 7. EXIT" + Environment.NewLine);

            Write(Environment.NewLine + "\tYour choose is: ");
            bool result = Byte.TryParse(ReadLine(), out choose);

            if (!result || choose > 7 || choose < 1) DisplayMenu();

            return choose;

        }

        static void GetFilesFromDirectory()
        {
            Clear();

            try
            {
                Write("Enter all the path of directory: ");
                string directory = ReadLine();

                DirectoryInfo di = new DirectoryInfo(directory);
                List<FileInfo> files = di.GetFiles().ToList();

                if (files.Count > 0)
                {
                    WriteLine();

                    foreach (FileInfo file in files)
                    {
                        WriteLine($"Full neme: {file.FullName} Name: {file.Name}");

                    }

                    if (files.Count > 1)
                    {
                        WriteLine(Environment.NewLine + $"There are {files.Count} files in the directory");

                    }
                    else
                    {
                        WriteLine(Environment.NewLine + "There is 1 file in the directory.");

                    }
                   
                }
                else
                {
                    WriteLine("There are no files into the directory!");

                }
            }
            catch (Exception ex)
            {
                WriteLine(Environment.NewLine + ex.Message);
              
            }

            ReadKey();

        }

        static void GetInfoAboutFile()
        {
            Clear();

            try
            {
                Write("Enter all path of directory with the file: ");
                string file = ReadLine();

                FileInfo fi = new FileInfo(file);

                WriteLine(Environment.NewLine + $"File name: {fi.Name}");
                WriteLine($"Full file name: {fi.FullName}");
                WriteLine($"Attributes: {fi.Attributes}");
                WriteLine($"Creation time: {fi.CreationTime}");
                WriteLine($"Last access time: {fi.LastAccessTime}");
                WriteLine($"Is read only file: {fi.IsReadOnly}");
                WriteLine($"Lenght: {fi.Length} bytes.");

            }
            catch (Exception ex)
            {
                WriteLine(ex.Message);
               
            }

            ReadKey();

        }

        static void RenameFile()
        {
            Clear();

            Write("Enter all the path with the file: ");
            string oldFile = ReadLine();

            Write("Enter only new name of the file: ");
            string newFile = ReadLine();

            try
            {
                FileInfo fi = new FileInfo(oldFile);

                fi.MoveTo(fi.Directory.FullName + "\\" + newFile);

                WriteLine(Environment.NewLine + "You renamed the file, successfully!" + Environment.NewLine);

            }
            catch (Exception ex)
            {
                WriteLine(ex.Message);
                              
            }

            ReadKey();

        }

        static void CopyFile()
        {
            Clear();

            Write("Write the all path with the file for copy: ");
            string oldFile = ReadLine();

            Write("Write the all path destination with the file: ");
            string newFile = ReadLine();

            try
            {
                File.Copy(oldFile, newFile);

                WriteLine(Environment.NewLine + "You copied the file, successfully" + Environment.NewLine);

            }
            catch (Exception ex)
            {
                WriteLine(ex.Message);
              
            }

            ReadKey();

        }

        static void MoveFile()
        {
            Clear();

            Write("Enter all the path with the file for move: ");
            string oldFile = ReadLine();

            Write("Enter all the path destination with the file: ");
            string newFile = ReadLine();

            try
            {
                File.Move(oldFile, newFile);

                WriteLine(Environment.NewLine + "You moved the file successfully!" + Environment.NewLine);

            }
            catch (Exception ex)
            {
                WriteLine(Environment.NewLine + ex.Message);
              
            }

            ReadKey();

        }

        static void DeleteFile()
        {
            Clear();

            Write("Enter all the path with the file for delete: ");
            string file = ReadLine();

            try
            {
                File.Delete(file);

                WriteLine(Environment.NewLine + "You deleted the file, successfully!");

            }
            catch (Exception ex)
            {
                WriteLine(Environment.NewLine + ex.Message);
               
            }

            ReadKey();

        }

    }
}

Kad pokrenete program dobićete sledeći meni:

                D I R E C T O R I E S

                         1. LIST ALL FILES FROM THE DIRECTORY

                         2. INFO ABOUT THE FILE

                         3. RENAME THE FILE

                         4. COPY THE FILE

                         5. MOVE THE FILE

                         6. DELETE THE FILE

                         7. EXIT


        Your choose is: 7

Opcijom 1 omogućeno vam je da izlistate sve fajlove u direktorijumu kojeg navedete.

Enter all path of the directory: c:\windows

Full name: c:\windows\avastSS.scr Name: avastSS.scr
Full name: c:\windows\bfsvc.exe Name: bfsvc.exe
Full name: c:\windows\bootstat.dat Name: bootstat.dat
Full name: c:\windows\DirectX.log Name: DirectX.log
Full name: c:\windows\DtcInstall.log Name: DtcInstall.log
Full name: c:\windows\explorer.exe Name: explorer.exe
Full name: c:\windows\HelpPane.exe Name: HelpPane.exe
Full name: c:\windows\hh.exe Name: hh.exe
Full name: c:\windows\hppcompiocomm.dll Name: hppcompiocomm.dll
Full name: c:\windows\lsasetup.log Name: lsasetup.log
Full name: c:\windows\MAXLINK.INI Name: MAXLINK.INI
Full name: c:\windows\mib.bin Name: mib.bin
Full name: c:\windows\multiflexio-plugins.xml Name: multiflexio-plugins.xml
Full name: c:\windows\multiflexio-plugins.xsd Name: multiflexio-plugins.xsd
Full name: c:\windows\multiflexio.dll Name: multiflexio.dll
Full name: c:\windows\netcomm.dll Name: netcomm.dll
Full name: c:\windows\notepad.exe Name: notepad.exe
Full name: c:\windows\PCDLIB32.DLL Name: PCDLIB32.DLL
Full name: c:\windows\PFRO.log Name: PFRO.log
Full name: c:\windows\Professional.xml Name: Professional.xml
Full name: c:\windows\regedit.exe Name: regedit.exe
Full name: c:\windows\scsicomm.dll Name: scsicomm.dll
Full name: c:\windows\setupact.log Name: setupact.log
Full name: c:\windows\setuperr.log Name: setuperr.log
Full name: c:\windows\splwow64.exe Name: splwow64.exe
Full name: c:\windows\system.ini Name: system.ini
Full name: c:\windows\twain_32.dll Name: twain_32.dll
Full name: c:\windows\usbcomm.dll Name: usbcomm.dll
Full name: c:\windows\win.ini Name: win.ini
Full name: c:\windows\WindowsShell.Manifest Name: WindowsShell.Manifest
Full name: c:\windows\WindowsUpdate.log Name: WindowsUpdate.log
Full name: c:\windows\winhlp32.exe Name: winhlp32.exe
Full name: c:\windows\WLXPGSS.SCR Name: WLXPGSS.SCR
Full name: c:\windows\WMSysPr9.prx Name: WMSysPr9.prx
Full name: c:\windows\write.exe Name: write.exe

There are 35 files in the directory.


Opcijom 2 dobijate neke osnovne podatke o navedenom fajlu.

Enter all path of directory with file: c:\test\test.txt

File name: test.txt
Full file name: c:\test\test.txt
Attributes: Archive
Creation time: 7/19/2016 2:45:06 AM
Last access time: 7/19/2016 2:45:07 AM
Is read only file: False
Length: 9013 bytes.


Opcija 3 vam služi da preimenujete fajl.

Enter all the path with the file: c:\test\test.txt
Enter only new name of the file: test1.txt

You renamed the file, successfully!

Opcija 4 vam omogućava kopiranje jednog fajla u drugi.

Write the all path with the file for copy: c:\test\test1.txt
Write all the path destination with the file: c:\test\test2.txt

You copied the file, successfully!


Opcijom 5 pomerate fajl iz jednog direktorijuma u drugi.

Enter all the path with the file for move: c:\test\test1.txt
Enter all the path destination with the file: c:\test\test\test1.txt

You moved the file, successfully!

I opcijom 6 brišete fajl koji navedete.

Enter all the path with the file for delete: c:\test\test\test1.txt

You deleted the file, successfully!


Kako navedeni program izgleda možete pogledati i na video-u:


( C# 6.0 Tutorial - Advanced - 45. Working With Files )

No comments:

Post a Comment