January 2008 Entries
I just ran up against a requirement to do a deep file and folder/directory copy in .NET (C# to be exact). A quick google didn't turn up any code, so I figured I'd post what I came up with. This is a somewhat naive implementation that may run out of steam for very deep folders or 1000s of files, but works great for most things. This implementation takes a source folder and a destination folder and copies the entire structure including files and folders from the source folder to the destination.
So without further ado:
private void CopyFolder(string folder, string destFolder)
{
Directory.CreateDirectory(destFolder);
foreach (string...
I needed a method to get the mime type of a System.Drawing Image instance that I'd loaded from an upload. All articles I was able to find online suggest some kind of lookup table solution. There's actually another way. Given an Image i, you can map from the i.RawFormat.Guid property to an ImageCodecInfo.FormatID. So it becomes a very simple for loop to get the MIME type of an image or bitmap. This works for any format System.Drawing/GDI+ supports (bmp, png, tiff, jpg/jpeg, etc). Here's the code:
public static string GetMimeType(Image i)
{
foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageDecoders())
{
if (codec.FormatID == i.RawFormat.Guid)
return codec.MimeType;
}
return "image/unknown";
}
This won't work for...
Sometimes you want to work with all controls on an ASP.NET page by type rather than id. I finally got fed up with the lack of builtin support, and wrote the following method that returns all controls inside another control (or page) by type:
public List<T> FindControls<T>(Control parent) where <T> : Control
{
List<T> foundControls = new List<T>();
FindControls<T>(parent, foundControls);
return foundControls;
}
void FindControls<T>(Control parent, List<T> foundControls) where <T> : Control
{
foreach (Control c in parent.Controls)
{
if (c is <T>)
foundControls.Add((<T>)c);
else if (c.Controls.Count > 0)
FindControls<T>(parent, foundControls);
}
}