marioz / madmilkman.ini Goto Github PK
View Code? Open in Web Editor NEWMadMilkman.Ini is a .NET component which simplifies processing of INI files.
License: MIT License
MadMilkman.Ini is a .NET component which simplifies processing of INI files.
License: MIT License
is there any way to clear a section as you can do wtih each key
I have no problem reading file but for some reason i can not update the values. I searched and found a simple sample
` Dim ini As New IniFile
ini.Load("C:\Users\Dropbox\Vodex\CNAME\cname.ini")
ini.Sections("Error").Keys("value").Value = "yes"`
When i debug and step over it i hit the ini.Load but it never hits the ini.Sections and the value is never updated ?
What am i missing ?
hi there
is there a way to decrypt an encrypted ini file?
I Make a project in .net5.0-Windows
can you modify or convert your app for that, Thanks
While the "LICENSE" file says it's under the MIT License, some files (MadMilkman.Ini/IniFile.cs
, MadMilkman.Ini/IniOptions.cs
, and MadMilkman.Ini/Properties/AssemblyInfo.cs
, to be specific) say they're under the Apache License, Version 2.0 in their copyright/license boilerplate. Sorry if this sounds demanding.
Hello! Sometimes I get an error that it is impossible to write to a file, but previously I used your library in a console application with the .NET Framework 4.7.2 and it always worked fine. And now I am using the library with a Windows Forms application and .NET Framework 4.8.0
My code (VB.NET):
Dim ini1 As New IniFile()
ini1.Load("set.ini")
ini1.Sections("main").Keys("valusd").Value = usdRate
ini1.Save("set.ini")
And the error log:
System.IO.IOException: The process cannot access the file 'D:\soft\set.ini' because the file is in use by another process.
in System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
in System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
in System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
in MadMilkman.Ini.IniFile.Save(String filePath)
in ReloadSoft.Form1.GetUsdRate() in D:\VS\project1\Form1.vb:line 191
in ReloadSoft.Form1.ConfigAndUsdRateTimer_Tick(Object sender, EventArgs e) in D:\VS\project1\Form1.vb:line 260
at System.Windows.Forms.Timer.OnTick(EventArgs e)
at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
You have not properly filled out your Apache License file leaving us with nothing to properly include in our projects.
https://github.com/MarioZ/MadMilkman.Ini/blob/master/LICENSE#L178-L189
I was testing ini file encryption (which works fine). I wanted to see what would happen if the encrypted file was modified in an editor. The result is that the load method throws a "System.Security.Cryptography.CryptographicException" which is perfectly reasonable since now the encrypted data is corrupt. The problem is that no matter what I do I can't catch the exception (placing the load call in the try block). Any help would be appreciated.
I want check exist before get key value:
Dim kValue As String = ini.Sections(sName).Keys(kName).Value.ToString
If (kValue = Nothing) Then
getConfig = kValue
else
getConfig = ''
end if
return error : Exception thrown: System.NullReferenceException at Dim kValue As String = ini.Sections(sName).Keys(kName).Value.ToString
how to check exist or null key before get it.
I have created a Console application to encrypt an INI file by your code examples.
Now I wanted to add a config.INI file in encrypted version in another Project so I encrypted it via Console App and loading in new Project .
It gives the following above error.
I came to know that this is an Cryptographic Exception can you please help me about it?
@MarioZ
Thanks in Advance.
Issue when reading INI file that has sections named as "[Segment[A]]", "[Segment[B]]", etc.
The IniSection objects have names as "Segment[A", "Segment[B", etc., they lose the ']' character.
Reported by: Jeffrey Curtis
I love the library you made.
I speak Korean, but the characters are broken like a question mark.
Even now, it is enough software,
If you provide multilingual support, I think more people will like it.
Thank you for making something good.
Written by your new followers.
Not sure why this is so touch even these days without having to rewrite file streams from scratch.....
Need to produce a simple ini with potentially blank sections containing only a linefeed that look like this:
[Section1](FULL CARRIAGE RETURN+LINEFEED HERE)
(LINEFEED HERE)
[Section2](FULL CARRIAGE RETURN+LINEFEED HERE)
(LINEFEED HERE)
Have it other than this assembly if I use a linefeed char as the key name even without a value still insists on placing the equals sign, otherwise would be correct.
Is this possible with this assembly, and if so what is the absolute simplest method without having to perform so much manual string manipulation that it's no different than just performing the standard filestream writer?
TIA!
Example:
[sektion]
key="Data Source=server;Initial Catalog=catalog;Integrated Security=SSPI"
Issue with accessing IniSectionCollection
indexer, an invalid cast exception occurs.
Issue is reproduced in VB.NET projects, but not in C# projects.
Reported by: Giakoumakis Nikos
Issue when reading following INI key:
suffix= LLC © 2016
The resulting IniKey's Value is trimmed; expected " LLC © 2016", actual "LLC © 2016".
Reported by: prakhar bansal
Use this structure in other projects and I had no problems, now I have the following error:
My config.ini
[Game]
GameSelect=DE
My code:
Dim setLang As String
Dim ini As New IniFile()
ini.Load("config.ini")
setLang = ini.Sections("Game").Keys("GameSelect").Value
Last line error:
System.InvalidCastException: 'Cannot convert an object of type' System.Collections.Generic.List1 [MadMilkman.Ini.IniSection]' to type 'System.Collections.Generic.IEnumerable`1 [MadMilkman.Ini.IniItem] '.'
My code works with:
Dim setLang As String
Dim ini As New IniFile()
ini.Load("config.ini")
setLang = ini.Sections(0).Keys(0).Value
VisualStudio 2019 Version 16.11.0
.NET Frameworks 3.5
MadMilkman.Ini 1.0.6
Tests:
.NET Frameworks 2.0 > NO
.NET Frameworks 3.0 > NO
.NET Frameworks 3.5 > NO
.NET Frameworks 4 > OK
.NET Frameworks 4.5 > OK
.NET Frameworks 4.6 > OK
.NET Frameworks 4.7 > OK
I have a static method that gets called, and I want to write to a .ini from that method. Is this possible?
I know this really isn't a question about MadMilkman.Ini and more of a question from someone who isn't super advanced in C#, but thanks in advance.
It seems I cannot serialize/deserialize values with custom type converter. Probably I'm doing something wrong, but code below seems okay to me:
[TypeConverter(typeof(ColorConverter))]
public class Color
{
public byte R { get; set; }
public byte G { get; set; }
public byte B { get; set; }
}
public class AppSettings
{
[IniSerialization("Color")]
public Color MyColor { get; set; }
}
class Program
{
static void Main(string[] args)
{
var file = new IniFile();
file.Load("D:/test.ini");
AppSettings deserialized = file.Sections["Settings"].Deserialize<AppSettings>();
AppSettings serialized = new AppSettings();
serialized.MyColor = new Color() { R = 128, G = 128, B = 128 };
TypeConverter colorTypeConverter = TypeDescriptor.GetConverter(serialized.MyColor);
Console.WriteLine(colorTypeConverter); // => Initest.ColorConverter
IniSection section = file.Sections.Add("Settings");
section.Serialize(serialized);
file.Save("D:/test.ini");
}
}
public class ColorConverter : TypeConverter
{
private Color[] standardValues;
public ColorConverter()
{
standardValues = new []
{
new Color() { R = 0, G = 0, B = 0 }
};
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(standardValues);
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string)
{
if (culture == null)
culture = CultureInfo.CurrentCulture;
string[] v = (value as string).Split(new string[] { culture.TextInfo.ListSeparator },
StringSplitOptions.RemoveEmptyEntries);
return new Color()
{
R = Convert.ToByte(v[0], culture),
G = Convert.ToByte(v[1], culture),
B = Convert.ToByte(v[2], culture)
};
}
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
Color color = value as Color;
StringBuilder s = new StringBuilder();
s.Append(color.R.ToString(culture.NumberFormat));
s.Append(culture.TextInfo.ListSeparator);
s.Append(' ');
s.Append(color.G.ToString(culture.NumberFormat));
s.Append(culture.TextInfo.ListSeparator);
s.Append(' ');
s.Append(color.B.ToString(culture.NumberFormat));
return s.ToString();
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override bool IsValid(ITypeDescriptorContext context, object value)
{
if (value is string)
{
return true;
}
return base.IsValid(context, value);
}
}
var list = new string[] { "one", "two", "three" };
var list2 = new List<string>() { "one", "two", "three" };
section2.Serialize(list2);
Hi,
could you please create a short sample of how to merge two .ini files? I am specifically interested to find out how to merge two .ini files with the same sections and keys. Which values will be used for which IniOptions property settings.
cheers,
JS
In VB.Net
I get an error when trying to count the key values for a specific section. It gives a Hex value.
Here is the code snippet for getting the keys when I supply a section name
Sub getMsgKeys2(SectionName As String)
Console.WriteLine("Start getMsgKeys2")
Dim iniFile As New Ini.IniFile(
New Ini.IniOptions() With {
.CommentStarter = Ini.IniCommentStarter.Semicolon,
.KeyDelimiter = Ini.IniKeyDelimiter.Colon,
.KeySpaceAroundDelimiter = False,
.SectionWrapper = Ini.IniSectionWrapper.SquareBrackets})
' Load file from path.
iniFile.Load("C:\Users\john\source\repos\Sbmr\tmp\ELGATO\HEADERS.DAT")
Dim KeysCount As Integer = iniFile.Sections(SectionName).Keys.Count
SBMRMain.RichTextBox1.Text = "Keys for " & SectionName & vbCrLf
For x As Integer = 0 To KeysCount
Console.WriteLine("Key- Name: {0}, Value: {1}, Count: {2} ", iniFile.Sections(SectionName).Keys(x).Name, iniFile.Sections(SectionName).Keys(x).Value, x)
Next
Console.WriteLine("End getMsgKeys2")
End Sub
There are 24 keys in the file. Works perfectly for x = 0 to x = 23, as expected, then the value generates an out of range exception for the last value which is a Hex value
iniFile.Sections(SectionName).Keys.Count = &H00000018
Here is a chunk of my my "ini" file
[80]
Utf8 = false
Message-ID: <[email protected]>
In-Reply-To: <[email protected]>
WhenWritten: 20210301163655-0600 4168
WhenImported: 20210301224012-0500 412c
WhenExported: 20210302044053Z 412c
ExportedFrom: ELGATO dove-general 1176
Sender: MRO
SenderNetAddr: VERT/BBSESINF
SenderIpAddr: 75.86.38.247
SenderHostName: cpe-75-86-38-247.wi.res.rr.com
SenderProtocol: Telnet
Organization: bbses.info
Subject: Re: GAB
To: Boondock
X-FTN-PID: Synchronet 3.18b-Win32 Sep 20 2020 MSC 1927
X-FTN-CHRS: CP437 2
Editor: FSEditor.js v1.104
WhenImported: 20210301143755-0800 41e0
WhenExported: 20210301144013-0800 41e0
ExportedFrom: VERT dove-gen 117335
WhenImported: 20210301163655-0600 4168
WhenExported: 20210301163751-0600 4168
ExportedFrom: BBSESINF dove-gen 3345
Conference: 2001
[380]
Utf8 = false
Message-ID: <[email protected]>
In-Reply-To: <[email protected]>
WhenWritten: 20210301163738-0600 4168
WhenImported: 20210301224012-0500 412c
WhenExported: 20210302044053Z 412c
ExportedFrom: ELGATO dove-general 1177
Sender: MRO
SenderNetAddr: VERT/BBSESINF
SenderIpAddr: 75.86.38.247
SenderHostName: cpe-75-86-38-247.wi.res.rr.com
SenderProtocol: Telnet
Organization: bbses.info
Subject: Re: GAB
To: Arelor
X-FTN-PID: Synchronet 3.18b-Win32 Sep 20 2020 MSC 1927
X-FTN-CHRS: CP437 2
Editor: FSEditor.js v1.104
WhenImported: 20210301143755-0800 41e0
WhenExported: 20210301144013-0800 41e0
ExportedFrom: VERT dove-gen 117336
WhenImported: 20210301163738-0600 4168
WhenExported: 20210301163751-0600 4168
ExportedFrom: BBSESINF dove-gen 3346
Conference: 2001
--- Continues after this ---
The only thing I can think of is the empty line between the last key value and the next section header...
Hi,
Thanks for this library. I have tested it in my vs2013. But i can't read value when i give section name and key name as string. I can read only when i give integers as section name and key name. But i see that in your examples, you used string for section name and key name. What to do ?
Note : I am using VB.Net
Hi Mario,
I am having some issues to update a single key value in the ini file consisting of many other sections and keys
This is a shortened version of my code:
Dim INI As New IniFile
INI.Load("C:\temp\settings.ini")
Dim section As IniSection = INI.Sections.Add("Settings")
section.Keys.Add("ColorTheme", "4")
INI.Save("c:\temp\settings.ini")
if I run the above code, the colortheme setting will get written to the ini file but the rest of the original ini entries are all deleted.
How do I avoid this? I just want to update a nominated key value.
Thanks
Hi,
is there a way to add a Key and value without adding a Section to the file?
Greetings!
Hi,
I have to deal with a 3rd party INI file that has multiple section of the same name but different keys inside. I haven´t seen a way to handle this case with MadMilkman.Ini, or am I wrong? I think I have to find my own approach, but if anybody has an idea, I would be greatful!
Example:
[DriveLetters]
DeviceID=1234567890
Letters=A
[DriveLetters]
DeviceID=0987654321
Letters=B
Hi,
Your component is working really well for me but I have an issue when determining how to handle a NullReferenceException
in VB.NET.
For example, I have global variables in my project and want to assign values that are stored in the ini file. This works great when the Keys are present in the ini file but when they are not I get a NullReferenceException
. I'd like to be able to handle this better and inform the user that a key was not found in the ini file.
Here's a block of code I'm using...
With iniFile.Sections("Settings")
...
strTest = .Keys("Test").Value
...
End With
If the key 'Test' doesn't exist or isn't spelled correctly in the 'Settings' section of the ini file, I get the NullReferenceException
. Is there a nice way to check if the key 'Test' exists first before attempting to load the value? I'd like to be able to deal with Key's that don't exist without it throwing the exception
Many thanks for this brilliant component.
I keep getting 'Property or indexer 'IniItemCollection.this[string]' cannot be assigned to -- it is read only".
Here is my code:
IniOptions options = new IniOptions();
IniFile file = new IniFile(options);
file.Load(@"Save Example.ini");
file.Sections["Section 1"].Keys["Key 1.1"] = "TEST";
How am I going to edit the value in the file? I can't seem to find it anywhere on documentation.
Title says it.
how can I set the checkbox.checkstate based of 0/1 value saved in the inifile?
Is it possible?
Hi,Can you add support to dotnet core 2.0?
Hi, I just started using this library, and I'm having some trouble.
I'm trying to write to the ini file, and it seems to be working, except it's duplicating the entire file, while still writing to the original section of the file.
Is there something I'm doing wrong?
Hi.
I'm working with a third-party app working with user-provided ini files (meaning that the files I'm gonna parse and edit can come from virtually anyone) so I can't use a custom convention, I have to follow the app's parser behavior.
It happens that this app considers any line that doesn't start with an identifier (key or section) as a comment. Results are that those lines are all valid comments:
# Hash
; semi-colon
: colon
// c-style comment
But in this app, a valid key identifier is @include
, meaning that it's not simply a matter of initial character, there's a story about parsing for an identifier.
How does MadMilkman.Ini's comment parsing works?
I can't tell from out of the box, but it surely doesn't parse my colon comment line (though it successfully parses all the others, so there's that).
How could I tell it to consider all those lines valid comments?
Or how could I tell it that @include
is a valid key identifier?
Thanks.
Hello,
I am having some trouble with this and I was wondering if I am doing something wrong or if there is a better way to do this.
Suppose I have the following sections, which all have the same section name...
[Test]
Length=10
Color=Red
Size=1
[Test]
Length=20
Color=Blue
Size=2
[Test]
Length=30
Color=Green
Size=3
What if I wanted to delete the 2nd section, where Color=blue?
I tried something like this...
For Each section As IniSection In ini.Sections.Where(Function(s) s.Name = "Radius")
If section.Keys("Color").Value = "Blue" Then
ini.Sections.Remove(section)
End If
Next
I am getting the following error in VisualStudio:
An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
Additional information: Collection was modified; enumeration operation may not execute.
Am I doing it wrong?
Could I get your permission to use ILMerge to merge your DLL into mine?
I'm making mods for a video game, and it would be really cool if I could reduce the amount of DLL files I need.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.