Thursday, May 15, 2008

C#: Convert System.Drawing.Color to Microsoft.Office.Interop.Word.WdColor

Using Microsoft.VisualBasic as an added reference to your C# projects, this is a smart way to convert Color to WdColor.

using VB = Microsoft.VisualBasic;
using Word = Microsoft.Office.Interop.Word;
...

Word.WdColor ConvertSystemColorToWdColor(System.Drawing.Color color)
{
int rgbColor = VB.Information.RGB(color.R, color.G, color.B);
Word.WdColor wdColor = (Word.WdColor)rgbColor;
return wdColor;
}

Monday, April 28, 2008

C#: Get MimeType from a File Name

private string GetMimeType (string fileName)
{
string mimeType = "application/unknown";
string ext = System.IO.Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null)
mimeType = regKey.GetValue("Content Type").ToString();
return mimeType;
}

Tuesday, March 18, 2008

C#: Handle new line characters ("\n") while saving text to file

New line charactars as observed in multi line TextBox or RichTextBox controls ("\n") often cause invalid characters to be saved in the file when it is saved. In order to appropriately handle new line characters, the following code can be used in stead of WriteLine:

FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.OpenOrCreate,FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
sw.Write(txtReturn.Text.Replace("\n",Environment.NewLine)); // Environment.NewLine is the real trick ;-)
sw.Dispose(); sw = null;
fs.Dispose(); fs = null;