Home » VB.Net

Reading and writing to ini files in Visual Basic 2010

I am trying to search for snippet for reading and writing ini files in visual basic .net. anyone has any idea?

3 Answers Found


Answer 1

The below Class was written several years ago but it should work in VB 2010:




Answer 2

Hello, I suggest to take for this a newer technique


The My.Settings object provides access to the application's settings and allows you to
dynamically store and retrieve property settings and other information for your application.
For more information, see Managing Application Settings.

regards Ellen


Answer 3

Hello teocs,

Thanks for your post.

The above replies have given you helpful suggestions. Here are two links about reading  and writing  INI files. Please check. Hope them helpful.

1. http://dog-net.org/content/development/vb-net/reading-and-writing-ini-files/  (Reading and Writing INI-Files)

2. An article describes a class library for reading/writing XML files, config files, ini  files, or the Registry using one simple interface.
(Read/Write XML files, Config files, INI files, or the Registry)

It is in C#, you could make a convertion by
Convert C# to VB.NET: http://www.developerfusion.co.uk/utilities/convertcsharptovb.aspx

If you have any problems, please feel free to follow up.

Best regards,
MSDN Subscriber Support in Forum
If you have any feedback on our support, please contact msdnmg@microsoft.com

Please mark the replies as answers if they help and unmark them if they provide no help. Welcome to the All-In-One Code Framework! If you have any feedback, please tell us. Thanks



 I am storing some data regarding Windows form postion and windows state in an INI file before closing the form.When we again opens the form i am reading the Form postions from ini file and dispaing the form at that postion.

Right now i am using some API calls to achive this functionality.Is there any direct way to Read Those data from ini file and Write into that ini file without usng API?

ini file contents:

[PANE Rep Information Area]

[PANE Tabbed Detail Area]


Code to read or write files from/to INI :

'API callsPublicDeclareFunction GetPrivateProfileString Lib"kernel32"Alias"GetPrivateProfileStringA" (ByVal lpApplicationName AsString, ByVal lpKeyName AsInteger, ByVal lpDefault AsString, ByVal lpReturnedString AsString, ByVal nSize AsInteger, ByVal lpFileName AsString) AsIntegerPublicDeclareFunction WritePrivateProfileString Lib"kernel32"Alias"WritePrivateProfileStringA" (ByVal lpApplicationName AsString, ByVal lpKeyName AsInteger, ByVal lpString AsInteger, ByVal lpFileName AsString) AsInteger'Function To read the Data from ini FIlePublicFunction ReadDimensions(ByRef sIniFile AsString, ByRef objForm As frmMngtWkBook) AsObjectDim sReturnString AsString = String.Empty
Dim tmpPtr As IntPtr
sReturnString = NewString(" ".c,20)

tmpPtr = Marshal.StringToHGlobalAnsi("Height")
        Dim g_objProfile AsNew BLCommon.clsProfile
          lReturnCode = GetPrivateProfileString(objForm.Name, tmpPtr, String.Empty, sReturnString, cReturnLength, sIniFile)
        EndTryIf lReturnCode > 0 Then
          objForm.Height = Strip(sReturnString) / 15
        EndIfEndFunction'Function To write the Data into ini FIlePublicFunction WriteDimensions(ByRef sIniFile AsString, ByRef objForm As frmMngtWkBook, OptionalByRef bIgnoreSplitter AsBoolean = False) AsObjectDim sInputString AsString = String.Empty
  Dim tmpPtr5 As IntPtr
  Dim tmpPtr6 As IntPtr
 sInputString = (objForm.Height *15).ToString().Trim()
 tmpPtr5 =Marshal.StringToHGlobalAnsi("Height")
          lReturnCode = WritePrivateProfileString(objForm.Name, tmpPtr5, tmpPtr6, sIniFile)
          sInputString = Marshal.PtrToStringAnsi(tmpPtr6)




I have installed VS2008 + VB Power Pack 3. When I try to create a VB6 Printer, It returns an unhandled error: ="Attempted to read or write protected memory"

The Test Code 1 as follows:

1.  Dim p As Microsoft.VisualBasic.PowerPacks.Printing.Compatibility.VB6.Printer
2.       For Each p In Microsoft.VisualBasic.PowerPacks.Printing.Compatibility.VB6.Printers
3.            If p.DeviceName = "Microsoft XPS Document Writer" Then
4.               p.Print("Print friom VB6 Comp ")
5.            End If
6.       Next

Error occurs: Line 2

The Test Code 2 as follows:

1. Dim Prt As New Microsoft.VisualBasic.PowerPacks.Printing.Compatibility.VB6.Printer
2. Dim msg As String = "String to measure"
3. With Prt
4.        .Print("Paper size is " & CStr(nHeight) & " by " & CStr(nWidth) & " twips")
5.           .EndDoc()
6.  End With

Error occurs: Line 1

How can I solve this problems?



I need to write and read data from a RS232 port. On the RS232 port there is a RFID Card reader-Writer connected.

So i need to send hex codes to the device, and have to poll every 1sec if there is a card in the system. if there is a card i need to read the info thet is on the card.

My biggest problem is i think is that i am not sure how many characters there will be in return after the read command (maybe it is always the same length this i am not sure)

Whatis the right way to read-write to the com port. so i always got the same result and not skipping a code.


best regards













I had VB2008 Express on my machine, registered.

I previously installed and used MS Visual Basic 2010 Express beta 2 ENU on XP SP3 machine.

Now it asked for Registration. So I tried. It complained I sould update to full 2010 release. So I tried this.

It didn't succeed. It complained about old beta 2 ENU Components that need to be uninstalled.

I removed everything named 2010 in Systems software.

I updated .net 4.0 beta 2 to full .Net 4.0.

Still it doesn't install. It still complains about old beta 2 ENU components I now cannot find.

What else should I do?

I think this Issue is relevant to all that installed VB 2010 beta 2 ENU

Thank You for any advice!


I use Visual Basic in Access, and I have no problem writing data directly to a cell in a database table. But I can not figure out how to write the code for Visual Basic 2008. For example I would use Me![cust_Cost] = 20 to input 20 in the database table.

I have purchased two different Books on Visual Basic 2008 and not one of them show how to input data manually.

Please If someone could give me just an example how to do it I would be very grateful.

Thank you, Krispy110



   Greetings of the day. First time I'm creating the ini file using SDK's WritePrivateProfileString function to create and write the string into the specified section of an initialization file.  I don't have much idea on ini file.

      My problem is, I want to indent the ini file with proper tabs, new lines and need to add comments in the ini file before each section. I googled, but unfortunate, I didn't get any help on this. The example Code line, just to illustrate:

WritePrivateProfileString(_T("USER DETAILS"), _T("Alias Name:"),
_T("Some Name \r\n"), "File Path")

   Could someone please help on this.



I am new to programming and have just finished one of my first projects. I would like to possibly sell this application, but I need to figure out how I'm going to get the app. protected.

I plan on selling the program as a digital download and was wondering what the steps would be to issue serial licenses to the people who will purchase it.

Can anyone please direct the first few steps? It would be greatly appreciated.

Aaron C.

Hi all and thanks for viewing my post.

I have two simple questions.

How can in include registry file when compiling my program?

I want to include an .ini to give the users the ability to change the database path for example


DATADIRECTORY            p:\data                                                                                              PROGRAMSDIRECTORY        c:\wami\programs\                                                                            REPORTSDIRECTORY         p:\reports\  

Can anyone show me how to program it, or is there a better way than using ini files?

I’m using visual studio 2008.


What would be the easiest way to read .INI file in C#.

[Domain\Domain Users]

... and extract those data.



I am trying to read a .INI file using C# . The .INI file has the following contents:

Rulespath = C:\DataScrubber\Rules\rules.xml
Reportpath = C:\\DataScrubber\\Reports\\Centricity_Extract_MPI_1_report.txt

I need to read the directory paths with C#. Is there an API that will let me do that?



I have a picture box that I am wanting to click on and open an excel file that is already created. If anyone can help me with the right code, or steps to take I would really appreciate it.  Thanks so much.



I have just installed the VBE 2010 version alongside the 2008 versions. When I get to the Start Page in VB, clicking on "Open Project" does nothing. Going to File > Open Project, does nothing and going to File > Open File does nothing. Which means I have no way of getting a project (or file) into VBE 2010. Is there anyone else with the same problem, and hopefully, a fix?

It also appears that C# suffers the exact same problem.



Hello, I am having trouble finding a code for visual basic 2010 (or 2008) that will compile batch files to a .exe format. (So they can no longer be edited.)

So far I've only found one program that does this (And was made in Visual Studios) and the program doesn't even actually work due to some unknown error. It'd be a great help to get a source code or just told that this isn't even possible.

-Thanks again,

United Utilities


Hi all.


I've just installed VB express 2010 from the full install ISO package.  I initially set the Help to use local files, but the default location doesn't exist, and although the tray icon says the library has started, I get Connection Refused.  To make matters worse, I can't find where to change it back to web help, so now I'm stuck as a newbie coder w/no help!  Please help me find some help :)



I've created a Help File - file extension .chm and I want to add it to a Visual Basic form.

I can't find a tutorial on how to do that.

Anyone know where I can get one?



When I try to open a project (created with Visual c# 2008 Express Edition) Visual Studio 2010 ultimate crash during conversion process without error and when I try to create a new project I receive this error: "error writing the project file. Interfaccia non registrata." Before reinstalling VS, I should try to find a solution.

Thanks for your help.




I've got an application which periodically writes to an XML file (every second or so). The file may be read by other applications, so when I want to write to it I get an exclusive read/write strem - not shared. This is my code:



bool timeOK = true;



fileStream = null;



(fileStream == null && timeOK)





fileStream =

File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);






// Update time variable



if(fileStream != null)




XmlDocument xmlDoc = newXmlDocument();



// Update the doc


// Save the doc

// Delete the current contents of the stream





// Create the settings


XmlWriterSettings xmlSettings = newXmlWriterSettings();

xmlSettings.Encoding =


xmlSettings.Indent =



// Create the file


using (XmlWriter writer = XmlWriter.Create(fileStream, xmlSettings))




// Make sure the buffers are completely flushed









I simply try for a specified amount of time (10 secs) or so to get the exclusive access. If I get the stream I load the xml doc then update it and save. When I try to save it I get an IO exception "The requested operation cannot be performed on a file with a user-mapped section open."

This really confuses me because I've a read/write stream with exclusive access! The only thing that I can think is that once I get the stream it is being closed somewhere in my code before I try to save the file with it, but despite looking over the code lots of times I just can't see anything wrong.

This problem happens once every few days, I've logged the errors and noticed that no virus scan / update or windows update was performed at this time, so I think I can eliminate that.

Any ideas???

Thanks in advance.........



Does the Win32 SDK function ReOpenFile have an equivalent method for a FileStream? Or is there another mechanism to convert a read-only file stream to a read-write file stream?



When I started to install the Visual Web Developer 2010 I came across an error that says that my computer installed the second beta version of the software Visual Basic and Visual C + + but after searching the Control Panel, My Computer and the RegEdit versions were not previously installed beta 2. I downloaded the Windows Install Cleanup and removed the software from there, but even after re-boot my computer unable to install having the same error ...

Who can help me Llosiar the beta versions of Visual Basic 2010?

Thanks in advance,

Can somebody point me to an example where I can export data to Excel 2007 via a VB in using Visual Studio 2010

<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure