VB.NET 2019 call WritePrivateProfileString , but doesn't work

Jack Tsai 0 Reputation points
2023-03-25T07:42:10.1133333+00:00

I using WritePrivateProfileString function call, but doesn't work. Is any one know what's wrong in this code call.


Imports System.Runtime.InteropServices
Imports System.Text

Public Class Form1

    Public Declare Function GetPrivateProfileString Lib "kernel32" _
        Alias "GetPrivateProfileStringA" _
        (ByVal lpApplicationName As String,
         ByVal lpKeyName As String,
         ByVal lpDefault As String,
         ByVal lpReturnedString As String,
         ByRef nSize As Integer,
         ByVal lpFileName As String) As Integer
    Public Declare Function WritePrivateProfileString Lib "kernel32" _
        Alias "WritePrivateProfileStringA" _
        (ByVal lpApplicationName As String,
        ByVal lpKeyName As String,
        ByVal lpString As String,
        ByVal lpFileName As String) As Integer

    Public Function WriteIniValue(section As String, key As String, keystring As String, filename As String) As String
        Dim sblen As Long

        Dim fi As New System.IO.FileInfo(filename)
        If Not fi.Exists Then
            Throw New Exception("the file doesn't exist(" & filename & ")")
        End If

        sblen = WritePrivateProfileString(section, key, keystring, filename)
        If sblen > 0 Then
            Return sblen
        Else
            Return 0
        End If
    End Function
    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        Debug.WriteLine(WriteIniValue("WINAPP", "PKG_EXEC", "2", "winapp.ini"))
    End Sub

the winapp.ini file and store in same path of a exec program.

; ini file
[WINAPP]
PKG_EXEC=1

The WriteIniValue always return 0 and use breakpoint track the section, the variable is correct call in.

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,580 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 112.5K Reputation points
    2023-03-25T08:14:28.6733333+00:00

    Try this:

    Dim p As String = Path.Combine(Application.StartupPath, "winapp.ini")
    Dim r = WriteIniValue("WINAPP", "PKG_EXEC", "2", p)
    
    0 comments No comments