Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Read/Write to .ini-file

Posted on 2010-11-17
4
Medium Priority
?
576 Views
Last Modified: 2013-11-26
Hi,

I have found this on the internet.
And I got no errors, but I don't know how to
call for it. In other words to make it work.
f.e. I have 2 buttons, one for reading to ini
and the other for writing to ini.
What do i have to put in these methodes.

Who knows the answer and is willing to help me?
Peter
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices; //nodig voor inifile

namespace iniFile
{
    public partial class Form1 : Form
    {
        //private string fileName;

        public Form1()
        {
            InitializeComponent();
        }

        public class IniFile
        {
            public string path;

            [DllImport("kernel32")]
            private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
            [DllImport("kernel32")]
            private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

            public IniFile(string INIPath)
            { path = INIPath; }

            public void IniWriteValue(string Section, string Key, string Value)
            { WritePrivateProfileString(Section, Key, Value, this.path); }

            public string IniReadValue(string Section, string Key, string Default)
            {
                StringBuilder temp = new StringBuilder(255);
                int i = GetPrivateProfileString(Section, Key, "", temp, 1024, this.path);
                return (temp.Length > 0) ? temp.ToString() : Default;
            }
        }




    }
}

Open in new window

0
Comment
Question by:peterkiers
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
4 Comments
 
LVL 5

Assisted Solution

by:Xper4net
Xper4net earned 400 total points
ID: 34154692
What do you want to do exactly?

These functions allow you :

> To read value :

If C:\MyIniFile.ini contains :

[MYSECTION]
MyKey=myvalue

IniFile myIniFile("C:\\MyIniFile.ini") ;

string entry = myIniFile.IniReadValue("MYSECTION", "MyKey", "defaultValue") ;

>> entry contains "myvalue"

if we had no MYSECTION or no MyKey entries, entry would contain "defaultValue"

> Now, if you write

myIniFile.IniWriteValue("MYSECTION", "MyKey", "newValue");

C:\MyIniFile.ini will contain :

[MYSECTION]
MyKey=newValue

Whatever this file had been existing or not, or were empty or not.




0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 400 total points
ID: 34154697
Well, what is it you are trying to do with the .ini file? Does it contain settings for this app itself? Is it an output created for some other application?

If you are trying to read settings for your own app, I would first suggest moving to the XML settings methodology. However, since I don't know your environment, I'll assume you must use the above functions. If the .ini file contains settings for your application, then you would probably want to read them in the Main() method of the application (in Program.cs) rather than in the constructor for your form (since constructors aren't supposed to throw exceptions and reading the .ini file has the potential to generate exceptions, although you could handle them in the constructor, I suppose).

Here would be an example of calling the code from main (based on your current code structure--i.e. nested classes):
static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Form1.IniFile iniObj = new Form1.IniFile("myini.ini");
        Form1 newForm1 = new Form1();

        // Read the application title from the settings file
        newForm1.Text = iniObj.IniReadValue("appSettings", "title", "My Super Snazzy App");

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(newForm1);
    }
}

Open in new window

0
 
LVL 70

Accepted Solution

by:
Éric Moreau earned 1200 total points
ID: 34154722
here you go:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices; //nodig voor inifile

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {

        IniFile _if; 

        public Form1()
        {
            InitializeComponent();

            _if= new IniFile(System.IO.Path.Combine(Application.StartupPath, "test.ini"));
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            string k1 = _if.IniReadValue("section", "key1", string.Empty);
            string k2 = _if.IniReadValue("section", "key2", string.Empty);
        }

        private void btnWrite_Click(object sender, EventArgs e)
        {
            _if.IniWriteValue("section", "key1", "value1");
            _if.IniWriteValue("section", "key2", "value2");
        }
    }


        public class IniFile
        {
            public string path;

            [DllImport("kernel32")]
            private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
            [DllImport("kernel32")]
            private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

            public IniFile(string INIPath)
            { path = INIPath; }

            public void IniWriteValue(string Section, string Key, string Value)
            { WritePrivateProfileString(Section, Key, Value, this.path); }

            public string IniReadValue(string Section, string Key, string Default)
            {
                StringBuilder temp = new StringBuilder(255);
                int i = GetPrivateProfileString(Section, Key, "", temp, 1024, this.path);
                return (temp.Length > 0) ? temp.ToString() : Default;
            }
        }
}

Open in new window

0
 
LVL 1

Author Comment

by:peterkiers
ID: 34154752
Thanks.

PK
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.

670 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question