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;
}
Monday, April 28, 2008
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;
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;
Monday, January 28, 2008
C#: Execute a windows batch script and wait for return
Unlike simply calling Process.Start("executable_name.exe","arguments") - which does not pause the parent C# process thread, use the below implementation for waiting for the batch script to finish executing before proceeding with the next set of instructions:
using System.Diagnostics;
Process proc = new Process();
proc.StartInfo.FileName = "C:\\myscript.bat";
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.Start();
proc.WaitForExit();
int exitCode = proc.ExitCode;
proc.Close();
using System.Diagnostics;
Process proc = new Process();
proc.StartInfo.FileName = "C:\\myscript.bat";
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.Start();
proc.WaitForExit();
int exitCode = proc.ExitCode;
proc.Close();
Subscribe to:
Posts (Atom)