Just another tech site

C# File Manipulation


USING

using System.IO;

FILE WATCHER

private StringBuilder RootDir = new StringBuilder("C:\\TEST\\");

private void Section_Watcher()
{
    Console.WriteLine("WATCHER -----------------------");

    <strong><span style="color:#ff0000;">FileSystemWatcher watcher = new FileSystemWatcher();</span></strong>
    watcher.Path = RootDir.ToString();
    watcher.NotifyFilter = <span style="color:#000000;">NotifyFilters</span>.LastAccess | <span style="color:#000000;">NotifyFilters</span>.LastWrite;
    watcher.Filter = "*.txt";

    // Add event handlers.
    watcher.<strong><span style="color:#ff0000;">Changed</span></strong> += <span style="color:#0000ff;">new</span> <span style="color:#000000;">FileSystemEventHandler</span>(fws_changed);
    watcher.<strong><span style="color:#ff0000;">Created</span></strong> += <span style="color:#0000ff;">new</span> <span style="color:#000000;">FileSystemEventHandler</span>(fws_created);
    watcher.<strong><span style="color:#ff0000;">Deleted</span></strong> += <span style="color:#0000ff;">new</span> FileSystemEventHandler(fws_deleted);
    watcher.<strong><span style="color:#ff0000;">Renamed</span></strong> += <span style="color:#0000ff;">new</span> RenamedEventHandler(fws_renamed);

    watcher.EnableRaisingEvents = true;
    Console.WriteLine("watcher started");
}

// HANDLERS
static void fws_changed(object sender, FileSystemEventArgs e)
{
     Console.WriteLine("DELEGATE[fws_changed]:[" + sender.ToString() + "]" + e.FullPath);
}
static void fws_created(object sender, FileSystemEventArgs e)
{
     Console.WriteLine("DELEGATE[fws_created]:[" + sender.ToString() + "]" + e.FullPath);
}
static void fws_deleted(object sender, FileSystemEventArgs e)
{
     Console.WriteLine("DELEGATE[fws_deleted]:[" + sender.ToString() + "]" + e.FullPath);
}
static void fws_renamed(object sender, FileSystemEventArgs e)
{
     Console.WriteLine("DELEGATE[fws_renamed]:[" + sender.ToString() + "]" + e.FullPath);
}

FILE, DIRECTORY and DRIVE LISTING

Listing of the directory, list files in the directory, and listing of the drives

private void Section_FileList()
{
    DirectoryInfo di = new <span style="color:#ff0000;">DirectoryInfo</span>(RootDir.ToString());
    Console.WriteLine("FILE LISTING -----------------------");
    foreach (FileInfo fiLocal in <strong><span style="color:#ff0000;">di.GetFiles()</span></strong>)
    {
         Console.WriteLine("File:{0}", fiLocal.Name);
    }
}

private void Section_DirList()
{
    DirectoryInfo di = new DirectoryInfo(RootDir.ToString());
    Console.WriteLine("DIR LISTING -----------------------");
    foreach (DirectoryInfo diLocal in <strong><span style="color:#ff0000;">di.GetDirectories()</span></strong>)
    {
         Console.WriteLine("Dir:" + diLocal.Name);
    }
}

private void Section_DriveList()
{
    Console.WriteLine("DRIVES -----------------------");
    foreach (DriveInfo dLocal in <strong><span style="color:#ff0000;">DriveInfo.GetDrives()</span></strong>)
    {
          Console.WriteLine("Drive:{0} {1}", dLocal.Name, dLocal.DriveType);
    }
}

FILE MANIPULATION

private void Section_FileOperation()
{
     Console.WriteLine("CREATE FILENAME-----------------------");

     <strong><span style="color:#ff0000;">FileInfo</span></strong> FiText = new FileInfo(RootDir.ToString() + OriginalBaseName + i + OriginalExtention);
     if (FiText.<strong><span style="color:#ff0000;">Exists</span></strong>)
     {
         Console.WriteLine("FiText:" + FiText.Name + " &gt;&gt;");
     }
     else
     {
          File.<strong><span style="color:#ff0000;">Create</span></strong>(RootDir.ToString() + OriginalBaseName + i + OriginalExtention);
          FiText = new FileInfo(RootDir.ToString() + OriginalBaseName + i + OriginalExtention);
          Console.WriteLine("Create the new file:" + FiText.Name);
      }

            Console.WriteLine("OPERATIONS -----------------------");
            try
            {
                i++;
                FiText.<strong><span style="color:#ff0000;">CopyTo</span></strong>(RootDir.ToString() + OriginalBaseName + i + OriginalExtention);
                Console.WriteLine("CopyTo");
            }
            catch (Exception Ex)
            {
                Console.WriteLine("CopyTo Failed Ex:"+Ex.Message);
            }

            // Move to
            try
            {
                i++;
                FiText.<strong><span style="color:#ff0000;">MoveTo</span></strong>(RootDir.ToString() + OriginalBaseName + i + OriginalExtention);
                Console.WriteLine("MoveTo");
            }
            catch (Exception Ex)
            {
                Console.WriteLine("MoveTo Failed Ex:" + Ex.Message);
            }
            // Move to
            try
             {
                 i++;
                 FiText.<strong><span style="color:#ff0000;">MoveTo</span></strong>(RootDir.ToString() + OriginalBaseName + i + OriginalExtention);
                 Console.WriteLine("MoveTo"); 
            }
             catch (Exception Ex)
             {
                 Console.WriteLine("CopyTo Failed Ex:"+Ex.Message);
             }
             try
             {
                 i++;
                 FiText.<strong><span style="color:#ff0000;">MoveTo</span></strong>(RootDir.ToString() + OriginalBaseName + i + OriginalExtention);
                 Console.WriteLine("MoveTo");
              }
             catch (Exception Ex)
             {
                 Console.WriteLine("MoveTo Failed Ex:" + Ex.Message);
             }
          }

COMPRESSION

.NET is providing a diferent types of compression

DeflateStream

Reference: http://msdn.microsoft.com/en-us/library/system.io.compression.deflatestream(v=VS.90).aspx

using System.IO;
using System.IO.Compression;




public static void Compress(FileInfo fi)
{
    // Get the stream of the source file.
    using (FileStream inFile = fi.OpenRead())
    {
        // Prevent compressing hidden and already compressed files.
        if ((File.GetAttributes(fi.FullName) &amp; FileAttributes.Hidden)
            != FileAttributes.Hidden &amp; fi.Extension != ".cmp")
        {
            // Create the compressed file.
            using (FileStream outFile = File.Create(fi.FullName + ".cmp"))
            {
                using (DeflateStream Compress = new DeflateStream(outFile, CompressionMode.Compress))
                {
                    // Copy the source file into 
                    // the compression stream.
                    byte[] buffer = new byte[4096];
                    int numRead;
                    while ((numRead = inFile.Read(buffer,
                            0, buffer.Length)) != 0)
                    {
                        Compress.Write(buffer, 0, numRead);
                    }
                    Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
                    fi.Name, fi.Length.ToString(), outFile.Length.ToString());
                }
            }
        }
    }
}

public static void Decompress(FileInfo fi)
{
    // Get the stream of the source file.
    using (FileStream inFile = fi.OpenRead())
    {
        // Get original file extension, 
        // for example "doc" from report.doc.cmp.
        string curFile = fi.FullName;
        string origName = curFile.Remove(curFile.Length
                - fi.Extension.Length);

        //Create the decompressed file.
        using (FileStream outFile = File.Create(origName))
        {
            using (DeflateStream Decompress = new DeflateStream(inFile,
                CompressionMode.Decompress))
            {
                //Copy the decompression stream into the output file.
                byte[] buffer = new byte[4096];
                int numRead;
                while ((numRead =
                    Decompress.Read(buffer, 0, buffer.Length)) != 0)
                {
                    outFile.Write(buffer, 0, numRead);
                }
                Console.WriteLine("Decompressed: {0}", fi.Name);
            }
        }
    }
}

GZipStream

Reference: http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream(v=VS.90).aspx

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Tag Cloud

%d bloggers like this: