using System; using System.IO; class MainClass { static void Main() { string tempFile = Path.GetTempFileName(); Console.WriteLine("Using " + tempFile); using (FileStream fs = new FileStream(tempFile, FileMode.Open)) { // (Write some data.) } // Now delete the file. File.Delete(tempFile); } }
File Stream
Get file Creation Time
/* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110 */ /* Example15_3.cs illustrates the File class */ using System; using System.Windows.Forms; using System.IO; public class Example15_3 { [STAThread] public static void Main() { // create and show an open file dialog OpenFileDialog dlgOpen = new OpenFileDialog(); if (dlgOpen.ShowDialog() == DialogResult.OK) { // use the File class to return info about the file string s = dlgOpen.FileName; Console.WriteLine("Filename " + s); Console.WriteLine(" Created at " + File.GetCreationTime(s)); Console.WriteLine(" Accessed at " + File.GetLastAccessTime(s)); } } }
Copy one folder to another folder
using System; using System.Collections.Generic; using System.Text; using System.IO; public class Main{ public static void Copy(string SourcePath, string TargetPath){ List<string> directories = new List<string>(); string tmpDestination; directories.Add(SourcePath); while (directories.Count > 0) { string directory = directories[0]; tmpDestination = directory.Replace(SourcePath, ""); if (tmpDestination.Length >= 1 && tmpDestination.Substring(0, 1) == "") { tmpDestination = tmpDestination.Substring(1); } tmpDestination = Path.Combine(TargetPath, tmpDestination); Directory.CreateDirectory(tmpDestination); foreach (string file in Directory.GetFiles(directory)) { FileInfo theFile = new FileInfo(file); File.Copy(file, Path.Combine(tmpDestination, theFile.Name)); } foreach (string tmpdir in Directory.GetDirectories(directory)) { directories.Add(tmpdir); } directories.RemoveAt(0); } } }
Append a suffix (such as a date) to the name of the 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 { #region Fields private static int unique; #endregion /// <summary> /// Append a suffix (such as a date) to the name of the file. /// </summary> /// <param name="filename"></param> /// <param name="suffix"></param> /// <returns></returns> public static string AppendSuffixToFilename(string filename, string suffix) { FileInfo fi = new FileInfo(filename); return string.Format(@"{0}{1}{2}{3}", fi.DirectoryName, Path.GetFileNameWithoutExtension(fi.FullName), suffix, fi.Extension ); } } }
Removes invalid file name characters from the specified string.
#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(); } } }
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; } } }