0

I am trying to write c# code to read key value from an ini file which doesnot contain a section header. As

 private static extern int GetPrivateProfileString(string section,       string key,string def, StringBuilder retVal,int size,string filePath);

function does not work in this case(as mentioned here) ,I tried to create another ini file with section header inserted . Then the GetPrivateProfileString function was used to read the key value. The ini file is getting created as expected, but the function is giving null value as result. Where have i gone wrong?

The code snippet is given below

//someFilePath contains .ini file 
string userFilePath = "someFilePath";
string sectionName = "TempSectionHeader";
string copyFile = "text.ini";
if (File.Exists(userFilePath))
{   
       if(File.Exists(copyFile))
       {
           File.Delete(copyFile);
       }

       File.AppendAllText("text.ini", "["+ sectionName + "]");
       string contents = File.ReadAllText(userFilePath);
       contents = contents.Replace("\0", "");
       File.AppendAllText(copyFile, "\r\n");
       File.AppendAllText(copyFile, contents);
       installName = ReadValueFromINIFile(sectionName, "installName", copyFile);
       MessageBox.Show(installName);
}
Community
  • 1
  • 1
Sree
  • 121
  • 1
  • 8
  • See if http://stackoverflow.com/questions/217902/reading-writing-an-ini-file helps. – qxg Oct 14 '16 at 09:41
  • Sounds like a bad idea. The linked post has a nice Linq answer by dtb, that is probably hard to top. - Also instead of `File.Exists(userFilePath)` why not `Directory.Exists(userFilePath)` ?? – TaW Oct 14 '16 at 22:09

1 Answers1

1

It's the path that is passed to GetPrivateProfileString that is wrong. Try using:

string installName = ReadValueFromINIFile(sectionName, "installName", Path.Combine(Application.StartupPath, copyFile));
  • Thanks. The path passed to GetPrivateProfileString was wrong `Path.Combine(AppDomain.CurrentDomain.BaseDirectory,copyFile) worked for me` – Sree Oct 17 '16 at 05:53