1.6. fejezet, Könyvtár kezelés, IO, környezeti változók

Input stream

using System;
using System.IO;
using System.Text;
 
namespace Homework4IO
{
    class Streams
    {
        static public void StreamInput()
        {
            FileStream fs = new FileStream("test.txt", FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("UTF-8"), false);
            string s = sr.ReadLine();
            while (s != null)
            {
                Console.WriteLine(s);
                s = sr.ReadLine();
            }
            sr.Close();
            fs.Close();
            Console.ReadKey();
        }
    }
}

Könyvtár struktúra

        static public void PrintFileSystemInfo(FileSystemInfo fsi)
        {
            if ((fsi.Attributes & FileAttributes.Directory) != 0)
            {
                DirectoryInfo di = fsi as DirectoryInfo;
                Console.WriteLine("Könyvtár: {0}, Készült: {1}", di.FullName, di.CreationTime);
            }
            else
            {
                FileInfo fi = fsi as FileInfo;
                Console.WriteLine("File: {0}, készült: {1}",
                fi.FullName, fi.CreationTime);
            }
        }
 
        static public void ReadDirectory()
        {
            foreach (string s in Directory.GetDirectories("C:\\"))
            {
                PrintFileSystemInfo(new DirectoryInfo(s));
            }
            foreach (string s in Directory.GetFiles(@"C:\")) //No escape character needed
            {
                PrintFileSystemInfo(new FileInfo(s));
            }
        }

MemoryStream

namespace StreamProject
{
    class Program
    {
        static void Main(string[] args)
        {
            MemoryStream mstream = new MemoryStream();
            StreamWriter sw = new StreamWriter(mstream);
            for (int i = 0; i < 1000; ++i)
            {
                sw.WriteLine(i);
            }
            sw.Flush();
            FileStream fs = File.Create("C:\\temp\\list.txt");
            mstream.WriteTo(fs);
            sw.Close();
            fs.Close();
            mstream.Close();
        }
    }
}

Könyvtár változásainak figyelése

namespace SwitchHostsForm
{
    partial class frmMain
    {
        delegate void UpdateHostsCallback();
        private FileSystemWatcher watcher;
        private void InitializeComponent()
        {
            watcher = new FileSystemWatcher();
            watcher.Path = Environment.GetEnvironmentVariable("SystemRoot") + "/system32/drivers/etc/";
            watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
            watcher.Filter = "hosts";
            watcher.Changed += this.OnChanged;
            watcher.EnableRaisingEvents = true;
        }
 
        public void OnChanged(object source, FileSystemEventArgs e)
        {
            UpdateHostsCallback d = new UpdateHostsCallback(this.reloadHosts);            
            this.Invoke(d);
        }
 
        public void reloadHosts()
        {
            String hostsContent = SwitchHosts.Program.getSystemHostsContent();
            lblHosts.Left = this.Right - rightMargin;
            lblHosts.Text = hostsContent;
        }
    }
}

Környezeti változók

Environment.CurrentDirectory = Environment.GetEnvironmentVariable("windir");
Environment.SetEnvironmentVariable("Test1", "Value1");
Environment.SetEnvironmentVariable("Test1", null);
 
foreach (DictionaryEntry de in Environment.GetEnvironmentVariables()) 
           Console.WriteLine("  {0} = {1}", de.Key, de.Value);

Fájlok és könyvtárak másolása, mozgatása és törlése

Copy:

        string fileName = "test.txt";
        string sourcePath = @"C:\Users\Public\TestFolder";
        string targetPath =  @"C:\Users\Public\TestFolder\SubDir";
 
        string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
        string destFile = System.IO.Path.Combine(targetPath, fileName);
 
        if (!System.IO.Directory.Exists(targetPath))
        {
            System.IO.Directory.CreateDirectory(targetPath);
        }
 
        System.IO.File.Copy(sourceFile, destFile, true);
 
        if (System.IO.Directory.Exists(sourcePath))
        {
            string[] files = System.IO.Directory.GetFiles(sourcePath);
 
            foreach (string s in files)
            {
                fileName = System.IO.Path.GetFileName(s);
                destFile = System.IO.Path.Combine(targetPath, fileName);
                System.IO.File.Copy(s, destFile, true);
            }
        }
        else
        {
            Console.WriteLine("Source path does not exist!");
        }
 
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();

Move:

        string sourceFile = @"C:\Users\Public\public\test.txt";
        string destinationFile = @"C:\Users\Public\private\test.txt";
 
        System.IO.File.Move(sourceFile, destinationFile);
        System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private");

Delete:

        if(System.IO.File.Exists(@"C:\Users\Public\DeleteTest\test.txt"))
        {
            try
            {
                System.IO.File.Delete(@"C:\Users\Public\DeleteTest\test.txt");
            }
            catch (System.IO.IOException e)
            {
                Console.WriteLine(e.Message);
                return;
            }
        }
 
        System.IO.FileInfo fi = new System.IO.FileInfo(@"C:\Users\Public\DeleteTest\test2.txt");
        try
        {
            fi.Delete();
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }
 
        try
        {
            System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest");
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }
 
        if(System.IO.Directory.Exists(@"C:\Users\Public\DeleteTest"))
        {
            try
            {
                System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest", true);
            }
 
            catch (System.IO.IOException e)
            {
                Console.WriteLine(e.Message);
            }
        }
 
        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@"C:\Users\Public\public");
        try
        {
            di.Delete(true);
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }

Common I/O Tasks