Append File methods

   
 

// crudwork
// Copyright 2004 by Steve T. Pham (http://www.crudwork.com)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with This program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.CodeDom.Compiler;
using System.Text.RegularExpressions;

namespace crudwork.Utilities
{
  /// <summary>
  /// File Utility
  /// </summary>
  public static class FileUtil
  {

    #region AppendFile methods
    /// <summary>
    /// Append a string value to a filename
    /// </summary>
    /// <param name="filename"></param>
    /// <param name="entry"></param>
    public static void AppendFile(string filename, string entry)
    {
      using (StreamWriter w = new StreamWriter(filename, true))
      {
        w.WriteLine(entry);
        w.Flush();
        w.Close();
      }
    }
    #endregion
   }
}

   
     


Write File methods

   
 
// crudwork
// Copyright 2004 by Steve T. Pham (http://www.crudwork.com)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with This program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.CodeDom.Compiler;
using System.Text.RegularExpressions;

namespace crudwork.Utilities
{
  /// <summary>
  /// File Utility
  /// </summary>
  public static class FileUtil
  {

    #region WriteFile methods
    /// <summary>
    /// Write a byte array to filename
    /// </summary>
    /// <param name="filename"></param>
    /// <param name="content"></param>
    public static void WriteFile(string filename, byte[] content)
    {
      int bufSize = 1024;
      try
      {
        using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read, bufSize))
        using (BinaryWriter w = new BinaryWriter(fs))
        {
          for (int i = 0; i < content.Length; i++)
          {
            w.Write(content&#91;i&#93;);
          }

          w.Flush();
          w.Close();
        }
      }
      catch (Exception ex)
      {
        throw;
      }
    }

    /// <summary>
    /// Write a string array to a file.
    /// </summary>
    /// <param name="filename"></param>
    /// <param name="content"></param>
    public static void WriteFile(string filename, string[] content)
    {
      try
      {
        using (StreamWriter w = new StreamWriter(filename, false))
        {
          for (int i = 0; i < content.Length; i++)
          {
            w.WriteLine(content&#91;i&#93;);
          }

          w.Flush();
          w.Close();
        }
      }
      catch (Exception ex)
      {
        
        throw;
      }
    }

    /// <summary>
    /// Write a string to a file.
    /// </summary>
    /// <param name="filename"></param>
    /// <param name="content"></param>
    public static void WriteFile(string filename, string content)
    {
      WriteFile(filename, new string[] { content });
    }
    #endregion
   }
}

   
     


Create Temp File

   
 
// crudwork
// Copyright 2004 by Steve T. Pham (http://www.crudwork.com)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with This program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.CodeDom.Compiler;
using System.Text.RegularExpressions;

namespace crudwork.Utilities
{
  /// <summary>
  /// File Utility
  /// </summary>
  public static class FileUtil
  {
        static int unique = 0;
    #region CreateTempFile
    /// <summary>
    /// Generate a unique temp filename with the extension specified.
    /// </summary>
    /// <param name="extension"></param>
    /// <returns></returns>
    public static string GenerateUniqueTempFilename(string extension)
    {
      string fstem = Path.GetRandomFileName();
      return String.Format("{0}@AutoGen_{1}_{2}.{3}", Path.GetTempPath(), fstem, ++unique, extension);
    }

    /// <summary>
    /// Write a string List array to a unique temporarily filename with the specify extension.
    /// </summary>
    /// <param name="extension"></param>
    /// <param name="list"></param>
    /// <returns></returns>
    public static string CreateTempFile(string extension, params string[] list)
    {
      try
      {
            TempFileCollection tempFiles = new TempFileCollection();
        string filename = GenerateUniqueTempFilename(extension);
        tempFiles.AddFile(filename, false);

        WriteFile(filename, list);

        return filename;
      }
      catch (Exception ex)
      {
        throw;
      }
    }
    #endregion
    /// <summary>
    /// Write a byte array to filename
    /// </summary>
    /// <param name="filename"></param>
    /// <param name="content"></param>
    public static void WriteFile(string filename, byte[] content)
    {
      int bufSize = 1024;
      try
      {
        using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read, bufSize))
        using (BinaryWriter w = new BinaryWriter(fs))
        {
          for (int i = 0; i < content.Length; i++)
          {
            w.Write(content&#91;i&#93;);
          }

          w.Flush();
          w.Close();
        }
      }
      catch (Exception ex)
      {
        throw;
      }
    }

    /// <summary>
    /// Write a string array to a file.
    /// </summary>
    /// <param name="filename"></param>
    /// <param name="content"></param>
    public static void WriteFile(string filename, string[] content)
    {
      try
      {
        using (StreamWriter w = new StreamWriter(filename, false))
        {
          for (int i = 0; i < content.Length; i++)
          {
            w.WriteLine(content&#91;i&#93;);
          }

          w.Flush();
          w.Close();
        }
      }
      catch (Exception ex)
      {
        
        throw;
      }
    }

    /// <summary>
    /// Write a string to a file.
    /// </summary>
    /// <param name="filename"></param>
    /// <param name="content"></param>
    public static void WriteFile(string filename, string content)
    {
      WriteFile(filename, new string[] { content });
    }    
   }
}

   
     


Make file writable and copy

   
 

// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com>
using System;
using System.IO;

namespace HtmlAgilityPack
{
    internal struct IOLibrary
    {
        internal static void MakeWritable(string path)
        {
            if (!File.Exists(path))
                return;
            File.SetAttributes(path, File.GetAttributes(path) &amp; ~FileAttributes.ReadOnly);
        }

        internal static void CopyAlways(string source, string target)
        {
            if (!File.Exists(source))
                return;
            Directory.CreateDirectory(Path.GetDirectoryName(target));
            MakeWritable(target);
            File.Copy(source, target, true);
        }
    }

}

   
     


Saves a file to an FTP server

   
 
/*
Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

#endregion

namespace Utilities
{
    public static class FileManager
    {
        /// <summary>
        /// Saves a file to an FTP server
        /// </summary>
        /// <param name="Content">File content</param>
        /// <param name="FileName">File name to save this as (should include directories if applicable)</param>
        /// <param name="FTPServer">Location of the ftp server</param>
        /// <param name="UserName">User name to log in</param>
        /// <param name="Password">Password to log in</param>
        public static void SaveFile(string Content, string FileName, Uri FTPServer, string UserName, string Password)
        {
            try
            {
                Uri TempURI = new Uri(Path.Combine(FTPServer.ToString(), FileName));
                FtpWebRequest FTPRequest = (FtpWebRequest)FtpWebRequest.Create(TempURI);
                FTPRequest.Credentials = new NetworkCredential(UserName, Password);
                FTPRequest.KeepAlive = false;
                FTPRequest.Method = WebRequestMethods.Ftp.UploadFile;
                FTPRequest.UseBinary = true;
                FTPRequest.ContentLength = Content.Length;
                FTPRequest.Proxy = null;
                using (Stream TempStream = FTPRequest.GetRequestStream())
                {
                    System.Text.ASCIIEncoding TempEncoding = new System.Text.ASCIIEncoding();
                    byte[] TempBytes = TempEncoding.GetBytes(Content);
                    TempStream.Write(TempBytes, 0, TempBytes.Length);
                }
                FTPRequest.GetResponse();
            }
            catch { }
        }

    }
}

   
     


Compares 2 files and determines if they are the same or not

   
 

/*
Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

#endregion

namespace Utilities
{
    public static class FileManager
    {
        /// <summary>
        /// Gets a files&#039; contents
        /// </summary>
        /// <param name="FileName">File name</param>
        /// <returns>a string containing the file&#039;s contents</returns>
        public static string GetFileContents(string FileName)
        {
            try
            {
                return GetFileContents(FileName, 5000);
            }
            catch { throw; }
        }

        /// <summary>
        /// Gets a files&#039; contents
        /// </summary>
        /// <param name="FileName">File name</param>
        /// <param name="TimeOut">Amount of time in ms to wait for the file</param>
        /// <returns>a string containing the file&#039;s contents</returns>
        public static string GetFileContents(string FileName, int TimeOut)
        {
            StreamReader Reader = null;
            int StartTime = System.Environment.TickCount;
            try
            {
                bool Opened = false;
                while (!Opened)
                {
                    try
                    {
                        if (System.Environment.TickCount - StartTime >= TimeOut)
                            throw new System.IO.IOException("File opening timed out");
                        Reader = File.OpenText(FileName);
                        Opened = true;
                    }
                    catch (System.IO.IOException e)
                    {
                        throw e;
                    }
                }
                string Contents = Reader.ReadToEnd();
                Reader.Close();
                return Contents;
            }
            catch
            {
                return "";
            }
            finally
            {
                if (Reader != null)
                {
                    Reader.Close();
                    Reader.Dispose();
                }
            }
        }
        /// <summary>
        /// Compares 2 files and determines if they are the same or not
        /// </summary>
        /// <param name="FileName1">name of the first file</param>
        /// <param name="FileName2">name of the second file</param>
        /// <returns>False if they are different, otherwise it returns true.</returns>
        public static bool CompareFiles(string FileName1, string FileName2)
        {
            try
            {
                FileInfo File1 = new FileInfo(FileName1);
                FileInfo File2 = new FileInfo(FileName2);
                if (File1.Length != File2.Length)
                {
                    return false;
                }
                string File1Contents = FileManager.GetFileContents(FileName1);
                string File2Contents = FileManager.GetFileContents(FileName2);
                if (!File1Contents.Equals(File2Contents))
                    return false;
                return true;
            }
            catch (Exception a)
            {
                throw a;
            }
        }


    }
}

   
     


Deletes files newer than the specified date

   
 
/*
Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

#endregion

namespace Utilities
{
    public static class FileManager
    {
        /// <summary>
        /// Determines if a directory exists
        /// </summary>
        /// <param name="DirectoryPath">Path of the directory</param>
        /// <returns>true if it exists, false otherwise</returns>
        public static bool DirectoryExists(string DirectoryPath)
        {
            try
            {
                return Directory.Exists(DirectoryPath);
            }
            catch (Exception a)
            {
                throw a;
            }
        }
        /// <summary>
        /// Gets a list of files
        /// </summary>
        /// <param name="DirectoryPath">Directory to check for files</param>
        /// <param name="Recursive">Determines if this is a recursive look at all directories under this one</param>
        /// <returns>a list of files</returns>
        public static List<FileInfo> FileList(string DirectoryPath, bool Recursive)
        {
            try
            {
                if (!Recursive)
                {
                    return FileList(DirectoryPath);
                }
                List<FileInfo> Files = new List<FileInfo>();
                if (DirectoryExists(DirectoryPath))
                {
                    DirectoryInfo Directory = new DirectoryInfo(DirectoryPath);
                    FileInfo[] SubFiles = Directory.GetFiles();
                    foreach (FileInfo SubFile in SubFiles)
                    {
                        Files.Add(SubFile);
                    }
                    DirectoryInfo[] SubDirectories = Directory.GetDirectories();
                    foreach (DirectoryInfo SubDirectory in SubDirectories)
                    {
                        List<FileInfo> TempFiles = FileList(SubDirectory.FullName, Recursive);
                        foreach (FileInfo File in TempFiles)
                        {
                            Files.Add(File);
                        }
                    }
                }
                return Files;
            }
            catch (Exception a)
            {
                throw a;
            }
        }
        /// <summary>
        /// Gets a list of files
        /// </summary>
        /// <param name="DirectoryPath">Directory to check for files</param>
        /// <returns>a list of files</returns>
        public static List<FileInfo> FileList(string DirectoryPath)
        {
            try
            {
                List<FileInfo> Files = new List<FileInfo>();
                if (DirectoryExists(DirectoryPath))
                {
                    DirectoryInfo Directory = new DirectoryInfo(DirectoryPath);
                    FileInfo[] SubFiles = Directory.GetFiles();
                    foreach (FileInfo SubFile in SubFiles)
                    {
                        Files.Add(SubFile);
                    }
                }
                return Files;
            }
            catch (Exception a)
            {
                throw a;
            }
        }
        /// <summary>
        /// Deletes files newer than the specified date
        /// </summary>
        /// <param name="Directory">Directory to look within</param>
        /// <param name="CompareDate">The date to compare to</param>
        /// <param name="Recursive">Is this a recursive call</param>
        public static void DeleteFilesNewerThan(string Directory, DateTime CompareDate, bool Recursive)
        {
            try
            {
                List<FileInfo> Files = FileManager.FileList(Directory, Recursive);
                foreach (FileInfo File in Files)
                {
                    if (File.LastWriteTime > CompareDate)
                    {
                        File.Delete();
                    }
                }
            }
            catch (Exception a)
            {
                throw a;
            }
        }

    }
}