Read INI file section with separator to array - c#

I'm trying to convert my C++ code to Visual C#. My goal is to be able to read a INI file (not a XML file !) with some sections. Each line is assigned to a button and each button launch a command. Each INI line has 4 value, separated by a ";".
For example :
[Button_section1]
Button1=Button Scenario;open;notepad;/a;scenario.txt
Means :
List item
Button1 : real name of the button
Button Scenario : the text (dipslayed name) of the button
open : initial command (can be print or explore too...
notepad : executable (can be any file or CMD for another example)
/a : first argument
scenario.txt : 2nd argument
So, in my previous code, I had 25 methods ReadSection and StringSepare, which was able to read each section of my INI file then put in array with the StringSepare method
When loading the form, the Button Text can be displayed from the INI file with following
Button bt = (Button)this.Controls.Find(i, true)[0];
Then clicking on the button allow to launch the following command :
(open in this case) -> notepad /a scenario.txt
NOTES :
I don't want to use any XML file, because I have a link with my SQL BD, which is interpretated as a CSV file. In fact, it is a CSV file with sections.,..

I also want to plug my own ini-parser library
https://github.com/rickyah/ini-parser
You can install it with NuGet, supports Mono and it's MIT licensed, also its really easy to use
// Load INI file from path, Stream or TextReader.
var p = new FileIniDataParser();
// ; is also the default comment string, you need to change it
p.Parser.Configuration.CommentString = "//";
// Load the file
IniData parsedData = parser.LoadFile("TestIniFile.ini");
// your information
var buttonData = parsedData["Button_section1"]["Button1"].Split(new {}[";"])
You can access the sections and keys in the sections directly if you want to gather the data about each button:
foreach(SectionData section in parsedData.Sections)
foreach(KeyData key in section.Keys)
Hope it is useful to you, and I accept PRs if you have any improvement ;)

Hi Benji you can use my library to help you process your INI files:
https://github.com/MarioZ/MadMilkman.Ini
For example:
// Set INI file's format options.
IniOptions option = new IniOptions();
// By default "CommentStarter" is ';' but you are using it as a
// multiple values separator so you need to change "CommentStarter"
option.CommentStarter = IniCommentStarter.Hash;
// Load INI file from path, Stream or TextReader.
IniFile ini = new IniFile(option);
ini.Load("Sample.ini");
// Select file's section.
IniSection sec = ini.Sections["Button_section1"];
// Select section's key.
IniKey key = sec.Keys["Button1"];
// Get key's values.
string[] values = key.Value.Split(';');
Also as an FYI, the library has a support for parsing multiple values (int-s, string-s, bool-s, etc.) but the syntax is different, it recognises the following:
Button1={Button Scenario,open,notepad,/a,scenario.txt}
With an above syntax you could do the following:
// Get key's values.
string[] values;
key.TryParseValue(out values);
Nevertheless I hope it's helpful to you, note that you can find additional samples in a sample projects (C# and C++/CLI) on the following link:
https://github.com/MarioZ/MadMilkman.Ini/tree/master/MadMilkman.Ini.Samples

Related

Reading from an app.config file

Given an app.config file, How can I read the keys and values given that those keys I am interested in will all follow a pattern I establish first. For example I do know that all the names of my keys will follow a pattern of
<add key="my_*_Def" value = "someValue">
The thing is I want to write a program that I can give these config files to it and then my program goes and finds that pattern in that file and gives them to me for further processing.
Is there a better way for writing this other than treating it as a text file and reading it line by line?
You can use
ConfigurationManager.AppSettings.AllKeys
to find all the keys in the app.config file. (link)
To try in another file, you'll want to get the configuration using ConfigurationManager.OpenExeConfiguration Method (String)
So;
var config = ConfigrationManager.OpenExeConfiguration("foo.exe.config");
var keys = config.AppSettings.AllKeys;

RollOver logic for logs with FileLogTraceListener

I am trying the following logging behavior:
•Create a new file daily
•When log file exceeds MaxFileSize, create a new file for that day with a new version number.
The first part works fine by setting LogFileCreationSchedule to LogFileCreationScheduleOption.Daily. My code looks something like this.
public class MyTraceListener : FileLogTraceListener
{
public MyTraceListener (): base()
{
this.LogFileCreationSchedule = LogFileCreationScheduleOption.Daily;
}
}
For the second part i was trying to write my own code to add the counter . But when i was going through the below link in msdn , it is mentioned that it would add an integer to the file name but which doesnt happening.
https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.logging.filelogtracelistener(v=vs.110).aspx
Few lines from the above link::
*Archival functionality. The log files generated by this class are named according to the base name and the date, along with a number to distinguish the log file from successive versions of the log. New log files are created on an as-needed basis.The explicit form of the file name is baseName[-dateStamp][-version].log, where:
◦The baseName part is the fundamental log name, specified by the BaseFileName property.
◦The dateStamp part has the format "YYYY-MM-DD", and it is shown when LogFileCreationSchedule is Daily or Weekly.
◦If more than one log file is needed with the same baseName and dateStamp, the version part, a positive Integer, is added to the file name.
Anyone tried using the Daily option and it created the file with number appended to the logfilename (DTM-2015-06-24_1) when it exceeded max size of 5MB which is default value.*
◦If more than one log file is needed with the same baseName and dateStamp, the version part, a positive Integer, is added to the file name.
The above scenario comes when the file is locked by another process.

Writing a JSON (or TXT) file in WPF C#

I have been trying to make sense of this http://msdn.microsoft.com/en-us/library/sfezx97z.aspx which uses the SaveFileDialog, but it is hard for me to understand. I have the following code:
FileInfo existingFile = new FileInfo("C:\\Users\\cle1394\\Desktop\\Apple Foreign Tax Payment Sample Layout Proposed - Sample Data.xlsx");
ConsoleApplication2.Program.ExcelData data = ConsoleApplication2.Program.GetExcelData(existingFile);
var json = new JavaScriptSerializer().Serialize(data);
How can I output the contents of json to a .json or .txt file?
I would like to let the user either see a link/ button to click to download/ save the file to a location on their computer, or, simply display the save file dialog box so that they can save the file to a location on their computer.
EDIT (to let OP comment on what parts are not clear):
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.ShowDialog();
if(saveFileDialog1.FileName != "")
{
File.WriteAllText(saveFileDialog1.FileName,json);
}
You are looking for this, then:
File.WriteAllText(#"c:\some\path\json.txt",json);
And note that it will save the file using UTF8-encoding without a Byte Order Mark. If you need the BOM, you need to use the File.WriteAllText(path, content, Enconding);
See here.
Update - adding sample with SaveFileDialog:
if(!string.IsNullOrEmpty(saveFileDialog.FileName))
{
//saveFileDialog.FileName should contain the full path
//according to the documentation: http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filename.aspx
File.WriteAllText(saveFileDialog.FileName,json);
}

How to make a C# Application work as the default program for certain files? [duplicate]

This question already has answers here:
Register file extension in window registry?
(3 answers)
Closed 8 years ago.
My application has a picture box in it. When I open an image in Windows, instead of the default program that opens to show that image, I want to use my own application and have that program containing the picture box show the image.
I did this recently, though I used a different action, not the default Open action.
First you find out file type of some extension, say .jpg:
var imgKey = Registry.ClassesRoot.OpenSubKey(".jpg")
var imgType = key.GetValue("");
Then you find out the path to your executable and build the "command string":
String myExecutable = Assembly.GetEntryAssembly().Location;
String command = "\"" + myExecutable + "\"" + " \"%1\"";
And register your executable to open files of that type:
String keyName = imgType + #"\shell\Open\command";
using (var key = Registry.ClassesRoot.CreateSubKey(keyName)) {
key.SetValue("", command);
}
You need to make some registry entries. First you need to associate the file extension with a class name (class name can be anything, just make it up).
So for example, if I wanted to associate .foo extensions with my Blah.exe program I would create the following registry entries (Note: In this case I'm associating .foo with a class called Foo.Document, then associated that class with my program):
Key: HKLM\SOFTWARE\Classes\.foo
Value: <default> = “Foo.Document”
Key: HKLM\SOFTWARE\Classes\Foo.Document
Value: <default> = “Foo Document”
Key: HKLM\SOFTWARE\Classes\Foo.Document\shell\open\command
Value: <default> = “[blah.exe]” “%1″
Your scenario makes me think that it's perfectly possible for you to simply select any JPG file, right click on the file, select "Open with" --> Choose default program, browse to your C# program and select the option "Always use the selected program to open this kind of file"
If you feel that you need to do this programmatically, you would need to set this on the Registry.
Here's a SO link that shows the process.
To set your app as default one for Jpeg files (example), you could:
Using Regedit.exe and goto item HKCR\.jpg\ and create subfolders like this shell\open\command.
Create there a new string value and edit default value as "path_to_exe" "%1"
Edit your EXE so that it can read arguments passed on command line and, if there is one, open it in picturebox (yeah, and many other controls as file does exists, file can be loaded in picturebox, etc...)

C#: How do you handle/parse messages for your applications like drag and dropping an associated file type?

C#: How do you handle/parse messages for your applications like drag and dropping an associated file type?
Let's say I have a text document application and I want it to execute and open a file if,
1.) a .txt document is dragged on top of the exe.
How could I make that possible, to execute the text software, and two, finally open and display the text document in the text document software?
You have to find where your Main method is declared to be sure its signature includes the args parameter, then you can check upon args array and you will find the complete pathname of the file dragged on your application's exe. Now you can then work with it accordingly to your needs.
Example:
static void Main(String[] args)
{
string p = args[0];
string e = Path.GetExtension(p);
if (e == ".txt")
{
// It's a text file
}
}
You can also drag more than a file and find their names inside the same array.
Remember that in my example i don't check if there are actually some elements in args array and thus i can get an IndexOutOfBoundException if nothing is dragged (or passed as argument) when launching the application and finally that using Path.GetExtension method doesn't assure you the file is what you think, but just it has that extension.
When someone drags-and-drops a text file on your application's executable, your app will get started and the path of the text file will be passed as a parameter. You should be able to examine it in your Main method.

Categories

Resources