#region License
// (c) Intergen.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
#endregion
using System;
using System.Text;
using System.IO;
using System.Web;
using System.Web.Hosting;
namespace Utilities.IO
{
public class FileUtils
{
/// <summary>
/// Removes invalid file name characters from the specified string.
/// </summary>
/// <param name="s">The filename string.</param>
/// <returns></returns>
public static string ToValidFileName(string s)
{
return ToValidFileName(s, string.Empty, null);
}
public static string ToValidFileName(string s, string invalidReplacement)
{
return ToValidFileName(s, invalidReplacement, null);
}
public static string ToValidFileName(string s, string invalidReplacement, string spaceReplacement)
{
StringBuilder sb = new StringBuilder(s);
foreach (char invalidFileNameChar in Path.GetInvalidFileNameChars())
{
if (invalidReplacement != null)
sb.Replace(invalidFileNameChar.ToString(), invalidReplacement);
}
if (spaceReplacement != null)
sb.Replace(" ", spaceReplacement);
return sb.ToString();
}
}
}
Month: February 2011
Create Thumbnail Image
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// * Neither the name of Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
namespace WOSI.Utilities
{
public class ImageUtils
{
public static Image CreateThumbnailImage(int width, int height, Image image, bool center)
{
// Create our new image
Bitmap newImage = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(newImage))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
if (center && image.Width != image.Height)
{
Rectangle srcRect = new Rectangle();
if (image.Width > image.Height)
{
srcRect.Width = image.Height;
srcRect.Height = image.Height;
srcRect.X = (image.Width - image.Height) / 2;
srcRect.Y = 0;
}
else
{
srcRect.Width = image.Width;
srcRect.Height = image.Width;
srcRect.Y = (image.Height - image.Width) / 2;
srcRect.X = 0;
}
g.DrawImage(image, new Rectangle(0, 0, newImage.Width, newImage.Height), srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, GraphicsUnit.Pixel);
}
else
{
g.DrawImage(image, 0, 0, width, height);
}
}
return newImage;
}
public static Image CreateThumbnailImage(int size, Image image, bool center)
{
return CreateThumbnailImage(size, size, image, center);
}
public static Image GetImageFromBytes(byte[] imageBytes)
{
try
{
using (MemoryStream ms = new MemoryStream(imageBytes))
{
Image image = Image.FromStream(ms);
return image;
}
}
catch
{
return null;
}
}
public static byte[] GetImageBytes(Image image, ImageFormat format)
{
byte[] imageBytes;
try
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, format);
imageBytes = ms.ToArray();
return imageBytes;
}
}
catch
{
return null;
}
}
}
}
removes invalid charactes from filenames, like the slash and backslash
//CruiseControl is open source software and is developed and maintained by a group of dedicated volunteers.
//CruiseControl is distributed under a BSD-style license.
//http://cruisecontrol.sourceforge.net/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace ThoughtWorks.CruiseControl.Core.Util
{
/// <summary>
/// Class with handy stirng routines
/// </summary>
public class StringUtil
{
/// <summary>
/// Removes leading and trailing quotes "
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public static string StripQuotes(string filename)
{
return filename == null ? null : filename.Trim('"');
}
/// <summary>
/// removes invalid charactes from filenames, like the slash and backslash
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static string RemoveInvalidCharactersFromFileName(string fileName)
{
return Strip(fileName, "", "/", ":", "*", "?", """, "<", ">", "|");
}
/// <summary>
/// removes the specified strings in the string array from the input string
/// </summary>
/// <param name="input"></param>
/// <param name="removals"></param>
/// <returns></returns>
public static string Strip(string input, params string[] removals)
{
string revised = input;
foreach (string removal in removals)
{
int i;
while ((i = revised.IndexOf(removal)) > -1)
revised = revised.Remove(i, removal.Length);
}
return revised;
}
}
}
Create Thumbnail
//http://activedeveloperdk.codeplex.com/
//The MIT License (MIT)
using System;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
using System.Configuration;
namespace ActiveDeveloper.Core.Utilities
{
public sealed class GDI
{
/// <summary>
///
/// </summary>
/// <param name="imagePathAndName"></param>
/// <param name="newHeight"></param>
/// <param name="newWidth"></param>
/// <returns>Name of the created thumbnail. E.g: small_thumb.jpg</returns>
public static string CreateThumbnail(string imagePathAndName, int newHeight, int newWidth )
{
using( Bitmap bitmap = new Bitmap( imagePathAndName ) ) {
Image thumbnail = bitmap.GetThumbnailImage( newWidth, newHeight, null, new IntPtr() );
FileInfo fileInfo = new FileInfo( imagePathAndName );
string thumbnailName = ConfigurationManager.AppSettings[ "ThumbnailAbr" ] + fileInfo.Name;
thumbnail.Save( fileInfo.Directory.ToString() + Path.DirectorySeparatorChar + thumbnailName );
return thumbnailName;
}
}
}
}
Get a 32×32 icon for a given file
//Microsoft Reciprocal License (Ms-RL)
//http://bmcommons.codeplex.com/license
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Text;
namespace BlueMirror.Commons
{
public static class Win32
{
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_DISPLAYNAME = 0x200;
public const uint SHGFI_TYPENAME = 0x400;
public const uint SHGFI_ATTRIBUTES = 0x800;
public const uint SHGFI_ICONLOCATION = 0x1000;
public const uint SHGFI_EXETYPE = 0x2000;
public const uint SHGFI_SYSICONINDEX = 0x4000;
public const uint SHGFI_LINKOVERLAY = 0x8000;
public const uint SHGFI_SELECTED = 0x10000;
public const uint SHGFI_LARGEICON = 0x0;
public const uint SHGFI_SMALLICON = 0x1;
public const uint SHGFI_OPENICON = 0x2;
public const uint SHGFI_SHELLICONSIZE = 0x4;
public const uint SHGFI_PIDL = 0x8;
public const uint SHGFI_USEFILEATTRIBUTES = 0x10;
private const uint FILE_ATTRIBUTE_NORMAL = 0x80;
private const uint FILE_ATTRIBUTE_DIRECTORY = 0x10;
[DllImport(“comctl32.dll”)]
private static extern int ImageList_GetImageCount(int himl);
[DllImport(“comctl32.dll”)]
private static extern int ImageList_GetIcon(int HIMAGELIST, int ImgIndex, int hbmMask);
[DllImport(“shell32.dll”)]
private static extern int SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, int cbfileInfo, uint uFlags);
private struct SHFILEINFO
{
public IntPtr hIcon;
public int iIcon;
public int dwAttributes;
public string szDisplayName;
public string szTypeName;
}
public enum FileIconSize
{
Small, // 16×16 pixels
Large // 32×32 pixels
}
// get a 32×32 icon for a given file
public static Image GetFileIconAsImage(string fullpath) {
return GetFileIconAsImage(fullpath, FileIconSize.Large);
}
public static Image GetFileIconAsImage(string fullpath, FileIconSize size) {
SHFILEINFO info = new SHFILEINFO();
uint flags = SHGFI_USEFILEATTRIBUTES | SHGFI_ICON;
if (size == FileIconSize.Small) {
flags |= SHGFI_SMALLICON;
}
int retval = SHGetFileInfo(fullpath, FILE_ATTRIBUTE_NORMAL, ref info, System.Runtime.InteropServices.Marshal.SizeOf(info), flags);
if (retval == 0) {
return null; // error occured
}
System.Drawing.Icon icon = System.Drawing.Icon.FromHandle(info.hIcon);
//ImageList imglist = new ImageList();
//imglist.ImageSize = icon.Size;
//imglist.Images.Add(icon);
//Image image = imglist.Images[0];
//icon.Dispose();
//return image;
return icon.ToBitmap();
}
public static Icon GetFileIcon(string fullpath, FileIconSize size) {
SHFILEINFO info = new SHFILEINFO();
uint flags = SHGFI_USEFILEATTRIBUTES | SHGFI_ICON;
if (size == FileIconSize.Small) {
flags |= SHGFI_SMALLICON;
}
int retval = SHGetFileInfo(fullpath, FILE_ATTRIBUTE_NORMAL, ref info, System.Runtime.InteropServices.Marshal.SizeOf(info), flags);
if (retval == 0) {
return null; // error occured
}
System.Drawing.Icon icon = System.Drawing.Icon.FromHandle(info.hIcon);
return icon;
}
public static Icon GetFolderIcon(string fullPath, FileIconSize size) {
SHFILEINFO info = new SHFILEINFO();
uint flags = SHGFI_USEFILEATTRIBUTES | SHGFI_ICON;
if (size == FileIconSize.Small) {
flags |= SHGFI_SMALLICON;
}
int retval = SHGetFileInfo(fullPath, FILE_ATTRIBUTE_DIRECTORY, ref info, System.Runtime.InteropServices.Marshal.SizeOf(info), flags);
if (retval == 0) {
return null; // error occured
}
System.Drawing.Icon icon = System.Drawing.Icon.FromHandle(info.hIcon);
return icon;
}
public static int GetFileIconIndex(string fullpath, FileIconSize size) {
SHFILEINFO info = new SHFILEINFO();
uint flags = SHGFI_USEFILEATTRIBUTES | SHGFI_SYSICONINDEX;
if (size == FileIconSize.Small) {
flags |= SHGFI_SMALLICON;
}
int retval = SHGetFileInfo(fullpath, FILE_ATTRIBUTE_NORMAL, ref info, System.Runtime.InteropServices.Marshal.SizeOf(info), flags);
if (retval == 0) {
return -1; // error
}
return info.iIcon;
}
public static int GetFolderIconIndex(string fullpath, FileIconSize size) {
SHFILEINFO info = new SHFILEINFO();
uint flags = SHGFI_USEFILEATTRIBUTES | SHGFI_SYSICONINDEX;
if (size == FileIconSize.Small) {
flags |= SHGFI_SMALLICON;
}
int retval = SHGetFileInfo(fullpath, FILE_ATTRIBUTE_DIRECTORY, ref info, System.Runtime.InteropServices.Marshal.SizeOf(info), flags);
if (retval == 0) {
return -1; // error
}
return info.iIcon;
}
public static void UpdateSystemImageList(ImageList imageList, FileIconSize size, bool isSelected, Image deletedImage) {
SHFILEINFO info = new SHFILEINFO();
uint flags = SHGFI_SYSICONINDEX;
if (size == FileIconSize.Small)
flags |= SHGFI_SMALLICON;
if (isSelected == true)
flags |= SHGFI_OPENICON;
int imageHandle = SHGetFileInfo(“C:”, 0, ref info, System.Runtime.InteropServices.Marshal.SizeOf(info), flags);
int iconCount = ImageList_GetImageCount(imageHandle);
for (int i = imageList.Images.Count; i < iconCount; i++) {
IntPtr iconHandle = (IntPtr)ImageList_GetIcon(imageHandle, i, 0);
try {
if (iconHandle.ToInt64() != 0) {
Icon icon = Icon.FromHandle(iconHandle);
imageList.Images.Add(icon);
icon.Dispose();
DestroyIcon(iconHandle);
}
}
catch {
imageList.Images.Add(deletedImage);
}
}
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public extern static bool DestroyIcon(IntPtr handle);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public extern static int SendMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);
[DllImport("winmm.dll", EntryPoint = "mciSendStringA")]
extern static void mciSendStringA(string lpstrCommand, string lpstrReturnString, long uReturnLength, long hwndCallback);
public static void Eject(string driveLetter) {
string returnString = "";
mciSendStringA("set cdaudio!" + driveLetter + " door open", returnString, 0, 0);
}
public static void Close(string driveLetter) {
string returnString = "";
mciSendStringA("set cdaudio!" + driveLetter + " door closed", returnString, 0, 0);
}
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public extern static uint RegisterWindowMessage(string lpString);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public extern static void SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public extern static int GetWindowLong(IntPtr hWnd, int nIndex);
// Constants and structs defined in DBT.h
public const int WM_DEVICECHANGE = 0x0219;
public const int DBT_DEVICEARRIVAL = 0x8000;
public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
public const int DBT_DEVNODES_CHANGED = 0x0007;
public enum DeviceType : int
{
OEM = 0x00000000, //DBT_DEVTYP_OEM
DeviceNode = 0x00000001, //DBT_DEVTYP_DEVNODE
Volume = 0x00000002, //DBT_DEVTYP_VOLUME
Port = 0x00000003, //DBT_DEVTYP_PORT
Net = 0x00000004 //DBT_DEVTYP_NET
}
public struct BroadcastHeader //_DEV_BROADCAST_HDR
{
public int Size; //dbch_size
public DeviceType Type; //dbch_devicetype
public int Reserved; //dbch_reserved
}
public struct Volume //_DEV_BROADCAST_VOLUME
{
public int Size; //dbcv_size
public DeviceType Type; //dbcv_devicetype
public int Reserved; //dbcv_reserved
public int Mask; //dbcv_unitmask
public int Flags; //dbcv_flags
}
[DllImport("kernel32.dll")]
public extern static long GetVolumeInformation(string PathName, StringBuilder VolumeNameBuffer, int VolumeNameSize, ref uint VolumeSerialNumber, ref uint MaximumComponentLength, ref uint FileSystemFlags, StringBuilder FileSystemNameBuffer, int FileSystemNameSize);
public static string GetVolumeSerialNumber(string drive) {
uint serNum = 0;
uint maxCompLen = 0;
StringBuilder volLabel = new StringBuilder(256);
uint volFlags = 0;
StringBuilder fileSystemName = new StringBuilder(256);
/* long ret = */ GetVolumeInformation(drive, volLabel, volLabel.Capacity, ref serNum, ref maxCompLen, ref volFlags, fileSystemName, fileSystemName.Capacity);
string serialNumberAsString = serNum.ToString("X");
serialNumberAsString.PadLeft(8, '0');
serialNumberAsString = serialNumberAsString.Substring(0, 4) + "-" + serialNumberAsString.Substring(4);
return serialNumberAsString;
}
// List View
public const int LVS_EX_DOUBLEBUFFER = 0x10000;
public const int LVM_FIRST = 0x1000;
public const int LVM_SETITEMSTATE = LVM_FIRST + 43;
public const int LVM_SETEXTENDEDLISTVIEWSTYLE = LVM_FIRST + 54;
public const int LVM_GETEXTENDEDLISTVIEWSTYLE = LVM_FIRST + 55;
public const int LVM_SETCOLUMNORDERARRAY = LVM_FIRST + 58;
public const int LVM_GETCOLUMNORDERARRAY = LVM_FIRST + 59;
public const int LVIF_STATE = 0x0008;
public const int LVIS_SELECTED = 0x0002;
public const int LVIS_FOCUSED = 0x0001;
[StructLayout(LayoutKind.Sequential)]
public struct LVITEM
{
public uint mask;
public int iItem;
public int iSubItem;
public uint state;
public uint stateMask;
public string pszText;
public int cchTextMax;
public int iImage;
public int lParam;
public int iIndent;
public int iGroupId;
public uint cColumns;
public uint puColumns;
}
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public extern static int SendMessage(IntPtr hWnd, UInt32 Msg, int wParam, ref LVITEM lvItem);
// Tree View Styles
public const int TV_FIRST = 0x1100;
public const int TVM_SETEXTENDEDSTYLE = TV_FIRST + 44;
public const int TVM_GETEXTENDEDSTYLE = TV_FIRST + 45;
public const int TVM_SETAUTOSCROLLINFO = TV_FIRST + 59;
public const int TVS_NOHSCROLL = 0x8000;
public const int TVS_EX_MULTISELECT = 0x0002;
public const int TVS_EX_DOUBLEBUFFER = 0x0004;
public const int TVS_EX_AUTOHSCROLL = 0x0020;
public const int TVS_EX_FADEINOUTEXPANDOS = 0x0040;
public const int GWL_STYLE = -16;
[DllImport("uxtheme.dll", CharSet = CharSet.Unicode)]
public extern static int SetWindowTheme(IntPtr hWnd, string pszSubAppName, string pszSubIdList);
}
}
[/csharp]
Copy from one file to another file
// Copyright (c) Microsoft Corporation. All rights reserved.
// This file is best viewed using outline mode (Ctrl-M Ctrl-O)
//
// This program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in.
// It is available from http://www.codeplex.com/hyperAddin
//
using System;
using System.IO;
namespace Utilities
{
static class StreamUtilities {
public static void CopyFromFile(string fromFilePath, Stream toStream)
{
using (Stream fromStream = File.OpenRead(fromFilePath))
CopyStream(fromStream, toStream);
}
public static void CopyToFile(Stream fromStream, string toFilePath)
{
using (Stream toStream = File.Create(toFilePath))
CopyStream(fromStream, toStream);
}
/// <summary>
/// CopyStream simply copies 'fromStream' to 'toStream'
/// </summary>
public static int CopyStream(Stream fromStream, Stream toStream)
{
byte[] buffer = new byte[8192];
int totalBytes = 0;
for (; ; )
{
int count = fromStream.Read(buffer, 0, buffer.Length);
if (count == 0)
break;
toStream.Write(buffer, 0, count);
totalBytes += count;
}
return totalBytes;
}
};
}
return true if the filename has the given attribute set
// 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 HasAttribute
/// <summary>
/// return true if the filename has the given attribute set
/// </summary>
/// <param name="filename"></param>
/// <param name="attr"></param>
/// <returns></returns>
public static bool HasAttribute(string filename, FileAttributes attr)
{
return (File.GetAttributes(filename) & attr) == attr;
}
#endregion
}
}

