Showing posts with label extension class. Show all posts
Showing posts with label extension class. Show all posts

July 29, 2010

StringCollection Class Extender

A helper class for the StringCollection class.
public static class StringCollectionExtender
{
    // Convert a string collection to a multiline string where
    // each entry in the collection becomes a line in 
    // multi-line string
    public static string ToMultilineString(
        this StringCollection sc)
    {
        StringBuilder res = new StringBuilder();
        foreach (string str in sc)
        {
            res.AppendLine(str);
        }
        return res.ToString();
    }

    public static string[] ToStringArray(
        this StringCollection sc)
    {
        string[] res = new string[sc.Count];
        sc.CopyTo(res, 0);
        return res;
    }

    // Convert a multiline string to a string collection with each line
    // of the string becoming a new entry in the collection
    public static StringCollection MultilineStringToStringCollection(
        string str)
    {
        string[] lines = str.Split('\r');
        StringCollection res = new StringCollection();
        foreach (string line in lines)
        {
            res.Add(line.Trim('\n'));
        }
        return res;
    }
}

July 28, 2010

Assembly Version Incrementor

Find and increment the assembly version info in an Assembly info file
public class AssemblyVersionIncrementor
{
    public void IncrementAssemblyVersionString(FileSystemInfo fileInfo)
    {
        string[] lines = File.ReadAllLines(fileInfo.FullName);
        lines = IncrementAssemblyVersionString(lines);
        File.WriteAllLines(fileInfo.FullName, lines);
    }

    internal string[] IncrementAssemblyVersionString(string[] lines)
    {
        string[] res = new string[lines.Length];
        int ix = 0;
        foreach (string line in lines)
        {
            res[ix++] = IncrementAssemblyVersionString(line);
        }
        return res;
    }

    // Could be modified to find other types of Version Info by
    // making the "AssemblyVersion" a parameter
    internal string IncrementAssemblyVersionString(string line)
    {
        string res = line;
        if (line.Contains("AssemblyVersion"))
        {
            string newLine = string.Empty;
            string str = line;
            // Check for comments
            int commentStart = line.IndexOf("//");
            // TODO /* ... */ style comments
            if (commentStart >= 0)
            {
                str = line.Substring(0, commentStart);
            }
            if (str.Contains("AssemblyVersion"))
            {
                int start = str.IndexOf('"') + 1;
                int end = str.IndexOf('"', start);
                string assemblyVerStr = str.Substring(start, end - start);
                Version av = new Version(assemblyVerStr);
                Version newVer = av.IncrementRevision();
                newLine = line.Substring(0, start) + newVer.ToString() + 
                    line.Substring(end, line.Length - end);
            }

            res = newLine.Length > 0 ? newLine : line;
        }

        return res;
    }
}
uses the following Version extension class:
internal static class VersionExtender
{
    public static Version Increment(this Version version)
    {
        return Increment(version, 0x1L);
    }

    public static Version IncrementMajor(this Version version)
    {
        return Increment(version, 0x1000000000000L);
    }

    public static Version IncrementMinor(this Version version)
    {
        return Increment(version, 0x100000000L);
    }

    public static Version IncrementBuild(this Version version)
    {
        return Increment(version, 0x10000L);
    }

    public static Version IncrementRevision(this Version version)
    {
        return Increment(version, 0x1L);
    }


    // Good demo of using >> and << operators as well
    private static Version Increment(this Version version, ulong inc)
    {
        ulong versnNum = (((ulong)version.Major & 0xFFFF) << 48) +
            (((ulong)version.Minor & 0xFFFF) << 32) +
            (((ulong)version.Build & 0xFFFF) << 16) +
            ((ulong)version.Revision & 0xFFFF);

        versnNum += inc;

        UInt16 major = (UInt16)(versnNum >> 48);
        UInt16 minor = (UInt16)((versnNum >> 32) & 0xFFFF);
        UInt16 build = (UInt16)((versnNum >> 16) & 0xFFFF);
        UInt16 revision = (UInt16)(versnNum & 0xFFFF);

        return new Version(major, minor, build, revision);
    }
}

July 16, 2010

FileSystemInfoExtender Class

Extend the FileSystemInfo class with enumerators to iterate through subdirectories, ditto with the DirectoryInfo class.
Now merged into this blog entry

December 15, 2009

GetRelativePath Helper

public static class FileSystemInfoExtender
{
    public static string GetPathRelativeTo(this FileSystemInfo file, string path)
    {
        string fullPath = Path.GetFullPath(path);
        string res = string.Empty;
        if (file.FullName.StartsWith(fullPath))
        {
            res = file.FullName.Substring(fullPath.Length);
        }
        res = res.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
        string sep = Path.DirectorySeparatorChar.ToString();
        if (res.StartsWith(sep))
        {
            res = res.Substring(1);
        }
        return res;
    }
}
and some tests
FileInfo file = new FileInfo(@"D:\Projects\smeg\src\blah\xxxx\whistle\stop\Carbuncle.cs");
string relPath = file.GetPathRelativeTo(@"D:\Projects\smeg\src");
Debug.Assert(relPath.Equals(@"blah\xxxx\whistle\stop\Carbuncle.cs", 
StringComparison.OrdinalIgnoreCase));
relPath = file.GetPathRelativeTo(@"D:/Projects/smeg/src");
Debug.Assert(relPath.Equals(@"blah\xxxx\whistle\stop\Carbuncle.cs", 
StringComparison.OrdinalIgnoreCase));
relPath = file.GetPathRelativeTo(@"D:\Projects\smeg\src\");
Debug.Assert(relPath.Equals(@"blah\xxxx\whistle\stop\Carbuncle.cs", 
StringComparison.OrdinalIgnoreCase));

August 5, 2008

File and Directory Classes

Generally it is best to use the FileSystemInfo (abstract base), FileInfo (for files), and DirectoryInfo (for directories) classes. Here is a class diagram to show how the 3 are related:
These classes are found in the "System.IO" namespace.

The "File" and "Directory" classes are used directly on strings:
Using System.IO;
...
// Determining If A File Is A Directory
private bool IsDirectory(string path)
{
    bool res = ((File.GetAttributes(path) & FileAttributes.Directory) ==
                FileAttributes.Directory);
    return res;
}

File.Exists(filname); // To check if a file exists
Directory.Exists(path) // To check if a directory exists

//To get the last time for the last change to a file use:
File.GetLastWriteTime(fileUri).ToString();
Some Iterators for iterating over Files and/or Directories recursively
public static class FileSystemInfoExtender
{
    // Iterate all files in a path, with 
    // an option to recurse through subdirectories
    public static IEnumerable<FileSystemInfo> 
      IterateFiles(this FileSystemInfo targ, bool recurse)
    {
        if (targ == null)
            throw new ArgumentNullException("targ");

        // return initial target
        yield return targ;

        if (recurse)
        {
            DirectoryInfo diTarg = targ as DirectoryInfo;
            // If targ is a directory
            if (diTarg != null)
            {                   
                // Get its contents as FileSystemInfo objects
                FileSystemInfo[] fsis = TryGetFileSystemInfos(diTarg);
                foreach (FileSystemInfo fsi in fsis)
                {
                    foreach (FileSystemInfo fsiInner in 
                        fsi.IterateFiles(recurse))
                        yield return fsiInner;
                }
            }
        }
    }

    // Iterate all files in a path, with 
    // recurse through subdirectories first
    public static IEnumerable<FileSystemInfo> 
        IterateFilesChildrenFirst(
          this FileSystemInfo targ, 
          bool recurse)
    {
        if (targ == null)
            throw new ArgumentNullException("targ");

        if (recurse)
        {
            DirectoryInfo diTarg = targ as DirectoryInfo;
            // If targ is a directory
            if (diTarg != null)
            {
                // Get its contents as FileSystemInfo objects
                FileSystemInfo[] fsis = TryGetFileSystemInfos(diTarg);
                foreach (FileSystemInfo fsi in fsis)
                {
                    foreach (FileSystemInfo fsiInner in
                        fsi.IterateFilesChildrenFirst(recurse))
                        yield return fsiInner;
                }
            }
        }

        // return initial target
        yield return targ;
    }


    private static FileSystemInfo[] TryGetFileSystemInfos(
      DirectoryInfo diTarg)
    {
        FileSystemInfo[] fsis = new FileSystemInfo[0];
        try
        {
            fsis = diTarg.GetFileSystemInfos();
        }
        catch (Exception ex)
        { 
            LogError("Calling GetFileSystemInfos() on \'" + diTarg.FullName + "\' threw " + 
                "an exception: " + ex.ToString());
        }
        return fsis;
    }

    // Iterate all directories in a path, with
    // an option to recurse through subdirectories
    public static IEnumerable<DirectoryInfo> IterateDirectories(
        this DirectoryInfo diTarg, bool recurse)
    {
        if (diTarg == null)
            throw new ArgumentNullException("diTarg");

        if (recurse) // return its children
        {
            DirectoryInfo[] dirs = TryGetDirectories(diTarg);
            foreach (DirectoryInfo dir in dirs)
            {
                foreach (DirectoryInfo dirInner in 
                    dir.IterateDirectories(recurse))
                {
                    yield return dirInner;
                }
            }
        }
        yield return diTarg; // return the current dir
    }

    private static DirectoryInfo[] TryGetDirectories(
        DirectoryInfo diTarg)
    {
        DirectoryInfo[] dirs = new DirectoryInfo[0];
        try
        {
            dirs = diTarg.GetDirectories();
        }
        catch (Exception ex)
        {
            LogError("Calling GetDirectories() on \'" +
                diTarg.FullName + 
                "\' threw " + 
                "an exception: " + 
                ex.ToString());
        }
        return dirs;
    }
 
    private static void LogError(string exStr)
    {
        Debug.WriteLine(exStr);
    }

    public static bool TryDeleteFileSystemInfo(this FileSystemInfo fsi)
    {
        bool success = true;
        try
        {
            fsi.Delete();
        }
        catch (Exception ex)
        {
            success = false;
            LogError("Delete \'" + 
                fsi.FullName + 
                "\' threw an exception: " +
                ex.ToString());
        }
        return success;
    }
}
for something similar check out the Directory.GetFiles(string path, string searchPattern, SearchOption searchOption); method

#region FileAttributesExtender

public static class FileAttributesExtender
{
    // Return lhs flags plus rhs flags
    public static FileAttributes Union(
        this FileAttributes lhs, FileAttributes rhs)
    {
        return lhs | rhs;
    }

    // Return flags common to lhs and rhs
    public static FileAttributes Intersection(
         this FileAttributes lhs, FileAttributes rhs)
    {
        return lhs & rhs;
    }

    // Return lhs flags minus rhs flags
    public static FileAttributes Difference(
         this FileAttributes lhs, FileAttributes rhs)
    {
        FileAttributes common = lhs & rhs;
        int res = (int)lhs - (int)common;
        return (FileAttributes)(res);
    }

    // Return true if lhs contains all the flags within rhs
    public static bool Contains(
         this FileAttributes lhs, FileAttributes rhs)
    {
        FileAttributes common = lhs & rhs;
        return (common == rhs);
    }

    // Return true if lhs contains one of the flags within rhs
    public static bool ContainsAnyOf(
        this FileAttributes lhs, FileAttributes rhs)
    {
        FileAttributes common = lhs & rhs;
        return ((int)common > 0);
    }

    // NON-extension methods here
    public static FileAttributes FromString(string source)
    {
        FileAttributes res = (FileAttributes)Enum.Parse(
             typeof(FileAttributes), source, true);
        return res;
    }

}

#endregion FileAttributesExtender
Sample usage to delete user files in their 'Temp' directory
private void DeleteTemporaryFiles(string tempPath)
{
  System.IO.DirectoryInfo targ = new 
         System.IO.DirectoryInfo(tempPath);
  bool success = false;
  foreach (System.IO.FileSystemInfo fsi in 
                     targ.IterateFiles(false))
  {
    Debug.Write(fsi.FullName);
    Debug.Write(" Attributes:" + fsi.Attributes.ToString("f"));
    if (!fsi.Attributes.ContainsAnyOf(
           System.IO.FileAttributes.System | 
           System.IO.FileAttributes.Temporary))
    {
      success = true;
      try
      {
        fsi.Delete();
      }
      catch (Exception ex)
      {
        success = false;
        Debug.Write(ex.ToString());
      }
      Debug.Write(success ? " Deleted" : " Could not Delete!");
    }
    Debug.WriteLine("");
  }
}