12 Jul

C# Read And Write A Registry Key

This example shows how to read and write a registry key. To do this, we must use RegistryKey and Registry classes in Microsoft.Win32 namespace.

Usage:

            //Usage:
            Write("REGISTRY DATA1", "http://www.csharpexamples.com");
            Write("REGISTRY DATA2", 123.ToString());

            string registryData1 = Read("REGISTRY DATA1");
            string registryData2 = Read("REGISTRY DATA2");

Sample Read and Write Methods:

        /// 
        /// This C# code reads a key from the windows registry.
        /// 
        /// 
        /// 
        public string Read(string keyName)
        {
            string subKey = "SOFTWARE\\" + Application.ProductName.ToUpper();

            RegistryKey sk = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(subKey);
            if (sk == null)
                return null;
            else
                return sk.GetValue(keyName.ToUpper()).ToString();
        }

        /// 
        /// This C# code writes a key to the windows registry.
        /// 
        /// 
        /// 
        public void Write(string keyName, string value)
        {
            string subKey = "SOFTWARE\\" + Application.ProductName.ToUpper();

            RegistryKey sk1 = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(subKey);
            sk1.SetValue(keyName.ToUpper(), value);
        }
12 Jul

Save A File With SaveFileDialog Using C#

This example shows how to save a file using the SaveFileDialog dialog box. SaveFileDialog allows users to set a file name for a specific file. It is found in System.Windows.Forms namespace and it displays the standard Windows dialog box.

Usage:

            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Title = "Save";
            saveDialog.Filter = "Text Files (*.txt)|*.txt" + "|" +
                                "Image Files (*.png;*.jpg)|*.png;*.jpg" + "|" +
                                "All Files (*.*)|*.*";
            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                string file = saveDialog.FileName;
            }
12 Jul

Select A File With OpenFileDialog Using C#

This example shows how to select a file using the OpenFileDialog dialog box. OpenFileDialog allows users to select files. It is found in System.Windows.Forms namespace and it displays the standard Windows dialog box.

Usage:

            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Title = "Select A File";
            openDialog.Filter = "Text Files (*.txt)|*.txt" + "|" + 
                                "Image Files (*.png;*.jpg)|*.png;*.jpg" + "|" +
                                "All Files (*.*)|*.*";
            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                string file = openDialog.FileName;
            }